当在编译时未知类型参数但是在运行时动态获取时,调用泛型方法的最佳方法是什么?
考虑以下示例代码 - 在Example()方法内部,GenericMethod<T>()使用Type存储在myType变量中调用的最简洁方法是什么?
public class Sample
{
public void Example(string typeName)
{
Type myType = FindType(typeName);
// What goes here to call GenericMethod<T>()?
GenericMethod<myType>(); // This doesn't work
// What changes to call StaticMethod<T>()?
Sample.StaticMethod<myType>(); // This also doesn't work
}
public void GenericMethod<T>()
{
// ...
}
public static void StaticMethod<T>()
{
//...
}
}
Run Code Online (Sandbox Code Playgroud) 我正在使用ChannelFactory编写WCF,它需要一个类型来调用CreateChannel方法.例如:
IProxy proxy = ChannelFactory<IProxy>.CreateChannel(...);
Run Code Online (Sandbox Code Playgroud)
在我的情况下,我正在做路由,所以我不知道我的渠道工厂将使用什么类型.我可以解析一个消息头来确定类型,但我在那里碰到了一堵砖墙,因为即使我有一个Type I实例也无法传递ChannelFactory期望泛型类型的实例.
用非常简单的术语重述这个问题的另一种方法是我试图做这样的事情:
string listtype = Console.ReadLine(); // say "System.Int32"
Type t = Type.GetType( listtype);
List<t> myIntegers = new List<>(); // does not compile, expects a "type"
List<typeof(t)> myIntegers = new List<typeof(t)>(); // interesting - type must resolve at compile time?
Run Code Online (Sandbox Code Playgroud)
我可以在C#中使用这种方法吗?
我想创建一个强类型列表并在运行时决定类型.这是我的代码.我认为它应该工作,但它没有:)
Type elementType = Type.GetType(parts[0].Trim(),false,true);
var elementsBeingSet = new List<elementType>();
Run Code Online (Sandbox Code Playgroud)
你有什么想法如何创建一个强类型列表,其类型我将在运行时决定?
重复:这是其他版本:
感谢 Jon Skeet 在这个问题中的回答,我进行了以下工作:
public delegate BaseItem GetItemDelegate(Guid itemID);
public static class Lists
{
public static GetItemDelegate GetItemDelegateForType(Type derivedType)
{
MethodInfo method = typeof(Lists).GetMethod("GetItem");
method = method.MakeGenericMethod(new Type[] { derivedType });
return (GetItemDelegate)Delegate.CreateDelegate(typeof(GetItemDelegate), method);
}
public static T GetItem<T>(Guid itemID) where T : class { // returns an item of type T ... }
}
public class DerivedItem : BaseItem { }
// I can call it like so:
GetItemDelegate getItem = Lists.GetItemDelegateForType(typeof(DerivedItem));
DerivedItem myItem = getItem(someID); // …Run Code Online (Sandbox Code Playgroud)