C# 动态返回内部类?
在下面的代码中。函数getInstance动态创建Aaa、Bbb和Ccc的实例。但是,如何动态生成Union3.Case2BB 动态创建泛型类型时必须使用:C# 动态返回内部类?,c#,.net,reflection,C#,.net,Reflection,在下面的代码中。函数getInstance动态创建Aaa、Bbb和Ccc的实例。但是,如何动态生成Union3.Case2BB 动态创建泛型类型时必须使用: Union3<Aaa, Bbb, Ccc> getInstance<Aaa, Bbb, Ccc>(int i) { Type t = typeof(Aaa); // implementation of getType(i) left out var instance = Activator.Creat
Union3<Aaa, Bbb, Ccc> getInstance<Aaa, Bbb, Ccc>(int i)
{
Type t = typeof(Aaa); // implementation of getType(i) left out
var instance = Activator.CreateInstance(t);
Type unionType = typeof(Union3<,,>).MakeGenericType(typeof(Aaa), typeof(Bbb), typeof(Ccc));
var nestedTypes = unionType.GetNestedTypes();
object unionInstance = null;
Type toCreate = null;
if (t == typeof(Aaa))
toCreate= nestedTypes.Single(x => x.Name == "Case1").MakeGenericType(typeof(Aaa), typeof(Bbb), typeof(Ccc));
else if (t == typeof(Bbb))
toCreate= nestedTypes.Single(x => x.Name == "Case2").MakeGenericType(typeof(Aaa), typeof(Bbb), typeof(Ccc));
else if (t == typeof(Ccc))
toCreate= nestedTypes.Single(x => x.Name == "Case3").MakeGenericType(typeof(Aaa), typeof(Bbb), typeof(Ccc));
else
throw new NotImplementedException();
unionInstance = Activator.CreateInstance(toCreate, instance);
return (Union3<Aaa, Bbb, Ccc>)unionInstance;
}
最终结果将是3个内部类中的一个具有正确项类型的实例。如果i==1,则返回新的Case1instance等??不确定你在问什么,因为你不能返回一个新的Union3,因为它是抽象的
Union3<Aaa, Bbb, Ccc> getInstance<Aaa, Bbb, Ccc>(int i)
{
Type t = typeof(Aaa); // implementation of getType(i) left out
var instance = Activator.CreateInstance(t);
Type unionType = typeof(Union3<,,>).MakeGenericType(typeof(Aaa), typeof(Bbb), typeof(Ccc));
var nestedTypes = unionType.GetNestedTypes();
object unionInstance = null;
Type toCreate = null;
if (t == typeof(Aaa))
toCreate= nestedTypes.Single(x => x.Name == "Case1").MakeGenericType(typeof(Aaa), typeof(Bbb), typeof(Ccc));
else if (t == typeof(Bbb))
toCreate= nestedTypes.Single(x => x.Name == "Case2").MakeGenericType(typeof(Aaa), typeof(Bbb), typeof(Ccc));
else if (t == typeof(Ccc))
toCreate= nestedTypes.Single(x => x.Name == "Case3").MakeGenericType(typeof(Aaa), typeof(Bbb), typeof(Ccc));
else
throw new NotImplementedException();
unionInstance = Activator.CreateInstance(toCreate, instance);
return (Union3<Aaa, Bbb, Ccc>)unionInstance;
}