C# 在实例化从泛型继承的类型时,是否有一种方法不使用dynamic?
如何创建从泛型继承的类型实例,并将其静态转换为其基类型C# 在实例化从泛型继承的类型时,是否有一种方法不使用dynamic?,c#,reflection,C#,Reflection,如何创建从泛型继承的类型实例,并将其静态转换为其基类型 foreach(Type t in x.ChildType.Assembly.GetTypes()) { if (t.BaseType.IsGenericType) { if (t.BaseType.GetGenericTypeDefinition() == typeof(ClassMapExt<>)) { if (t.BaseType.GetGeneri
foreach(Type t in x.ChildType.Assembly.GetTypes())
{
if (t.BaseType.IsGenericType)
{
if (t.BaseType.GetGenericTypeDefinition() == typeof(ClassMapExt<>))
{
if (t.BaseType.GetGenericArguments()[0] == x.ChildType)
{
// t is BonusMap. BonusMap is declared as:
// class BonusMap : ClassMapExt<Bonus>
dynamic bz = Activator.CreateInstance(t);
// the last line is analogous to:
// var bz = new BonusMap();
// statically casting it doesn't work
// var bz = (ClassMapExt<>) Activator.CreateInstance(t);
foreach (IManyToOneMappingProvider imt1 in bz.ExtReference)
foreach(x.ChildType.Assembly.GetTypes()中的类型t)
{
if(t.BaseType.IsGenericType)
{
if(t.BaseType.GetGenericTypeDefinition()==typeof(ClassMapExt))
{
if(t.BaseType.GetGenericArguments()[0]==x.ChildType)
{
//t是BonusMap。BonusMap声明为:
//类BonusMap:ClassMapExt
动态bz=Activator.CreateInstance(t);
//最后一行类似于:
//var bz=new BonusMap();
//静态铸造不起作用
//var bz=(ClassMapExt)Activator.CreateInstance(t);
foreach(iManytooneMapping在bz.Extreefence中提供imt1)
通常的方法是在其中包含一个非通用API(可能带有显式实现)。然后您只需转换到非通用接口
不太一样,但有点像:
Type itemType = ...;
IList list = (IList)Activator.CreateInstance(
typeof(List<>).MakeGenericType(itemType));
list.Add(...);
Type itemType=。。。;
IList list=(IList)Activator.CreateInstance(
typeof(List).MakeGenericType(itemType));
添加(…);