泛型列表方法指定类型
在Java中,我可以有一个方法声明是这样的:泛型列表方法指定类型
<T> List<T> getList(final Class<T> objectClass, String whatever)
这意味着我通过指定类的方法指定列表返回类型。
List<Customer> customers = getList(Customer.class, "blah");
如果我没有正确指定的类我得到一个编译时错误。 (这就是我正在寻找的东西 - 我希望编译器捕捉不匹配)。
List<String> customers = getList(Customer.class, "blah"); // will not compile
在C#中相当于什么? TIA
C#中没有办法让编译器根据返回类型推断泛型类型。
List<Customer> customer = getList<Customer>("blah");
这个方法应该写成:
在C#中,你必须要是唯一的区别是返回类型指定牛逼
List<T> getList<T>(string whatever) { ... }
然而,在C#中,类型推断是自动如果有一个参数需要某种类型的客户,则进行处理。例如,你可以有:
List<T> MakeList<T>(params T[] items) { ...}
然后调用此为(无<Customer>
):响应
Customer one = GetCustomer(1);
Customer two = GetCustomer(2);
var customers = MakeList(one, two);
编辑评论:
如果你将要构建一个新的“客户”在你的方法中,并且希望这可以用于任何类型,你需要一个新的约束。有这样的:
你会需要这样的东西:
List<T> GetList<T>(string whatever)
where T : new() // This lets you construct it internally
{
List<T> results = new List<T>();
/// ...
T newInstance = new T();
results.Add(newInstance);
return results;
}
话虽这么说,如果你打算做一个方法是这样,那么你还需要有一个约束的接口,所以你可以设置你创建对象:
List<T> GetList<T>(string whatever)
where T : ISomeInterface, new()
这将让你使用的ISomeInterface
性能的方法中,以及将其限制为只与即时通讯工作类型感谢那个接口。
试试这个:
List<T> getList<T>(String whatever) {
.
.
.
.
}
此任务调用者指定T的类型,而调用方法。
但是在这种情况下的语法我不能引用吨的方法体来知道哪种类型的对象实例化。 – sproketboy
@Dan:就我所知,问题中没有提到这个要求。也许你应该编辑它来反映你实际想问的问题。 – jalf
您可以在该方法中使用typeof(T)。 – Chandu
我认为这只是
List<T> GetList<T>(string whatever) { /* ... */ }
你可以把一个约束对T像
List<T> GetList<T>(string whatever)
where T : class
{ /* ... */ }
,如果你想将它约束上课。
<T> List<T> getList(final Class<T> objectClass, String whatever)
到:
List<T> GetList<T>(string whatever)
List<Customer> customers = getList(Customer.class, "blah");
到:
List<String> customers = getList(Customer.class, "blah");
//将无法编译
到:
List<string> = GetList<Customer>("blah"); // will not compile too
的两种语言如此接近
那么,如何在该方法可以确定哪种类型实例化添加到我的列表? – sproketboy
@Dan:我刚刚编辑过 - 看看是否能回答你的问题......(跨语言概念总是很棘手,因为它们在C#和Java中并不完全相同) –
谢谢。那块石头! :) – sproketboy