我需要将一个通用类型参数传递给一个接口。我有一个包含类型名称的字符串。
我有类似于以下内容的代码:
string type = "ClassType";
Type t = Type.GetType("ClassType");
IProvider<t> provider = (IProvider<t>)someObject;
这个方法对我来说不起作用,正确的做法是什么?谢谢。
我需要将一个通用类型参数传递给一个接口。我有一个包含类型名称的字符串。
我有类似于以下内容的代码:
string type = "ClassType";
Type t = Type.GetType("ClassType");
IProvider<t> provider = (IProvider<t>)someObject;
这个方法对我来说不起作用,正确的做法是什么?谢谢。
这里是一个使用反射加载泛型类型的示例。
using System;
namespace GenericCastRuntime
{
class Program
{
static void Main(string[] args)
{
string type = "GenericCastRuntime.Program+Provider`1";
Type t = Type.GetType(type);
string genericType = "System.String";
Type gt = Type.GetType(genericType);
var objType = t.MakeGenericType(gt);
var ci = objType.GetConstructor(Type.EmptyTypes);
var obj = ci.Invoke(null);
IProvider provider = obj as IProvider;
}
public class Provider<T> : IProvider<T>
{
public T Value { get; set; }
object IProvider.Value
{
get { return this.Value; }
set
{
if (!(value is T)) throw new InvalidCastException();
this.Value = (T)value;
}
}
}
public interface IProvider { object Value { get; set; } }
public interface IProvider<T> : IProvider { T Value { get; set; } }
}
}
这是一个简单的例子:
public static object DynamicallyCreateGeneric(Type GenericTypeSource, Type SpecificTypeSource)
{
System.Type SpecificType =
GenericTypeSource.MakeGenericType(
new System.Type[] { SpecificTypeSource }
);
return Activator.CreateInstance(SpecificType);
}
...然后,例如:
string type = "System.String";
Type t = Type.GetType(type);
var DynamicallyCreatedGeneric = DynamicallyCreateGeneric(typeof(List<>), t);
System.Diagnostics.Debugger.Break();
根据您的实现和口味进行调整。当然,这种方法并不理想。泛型最好的部分之一是类型编译器级别的类型安全性。