我可能会错误地说出标题的错误,如果这已经得到解答我会道歉(我还没有找到)。
说过我已经搜索过这个网站好几个小时,并且遇到了几个非常复杂的尝试(不够清楚)使用反射,我不想因为性能原因而使用反射。我已经在使用Type.GetType()搜索.dll来查找类型。
所以,不用多说了,这里就是..
我在类中接受泛型类型的方法:
public class SomeClass
{
public TList Execute<TList, TItem>(string text)
where TList : ICollection<TItem>, new()
where TItem : new()
{
TList list = new TList();
TItem item = new TItem();
...set properties and add to list...
...implementation not important...
return list;
}
}
用法(调用方法):
public void callingMethod(string typeNameString, string typeItemNameString)
{
Type T = Type.GetType(typeNameString);
Type Ti = Type.GetType(typeItemNameString);
SomeClass sc = new SomeClass();
// and here is where things falls apart drastically..
// not sure exactly what to do here as it seems noting works
var result = sc.Execute<T,Ti>("hello text"); //no luck..'T' is a variable but used as a type
var result = sc.Execute<Type.GetType(typeNameString),Ti>("hello text"); //no luck...operator '<' cannot be appliedto operands of type 'method group' and 'Type'
//This works fine
List<Invoice> _invoices = sc.Execute<Invoices, Invoice>("hello text");
}
public class Invoice
{ //properties omitted }
public class Invoices : List<Invoice>
{}
这似乎是一种非常直接/合乎逻辑的方法,但事实证明并非如此。
我错过了什么?
我感谢个人在这个论坛上回答问题的时间和奉献精神。
答案 0 :(得分:1)
您无法使用&lt;&gt;表示法,因为编译器实际上创建了内置类型的类。因此必须在编译时知道它。对于你想要做的事情,你必须使用反射。