Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/273.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 动态返回内部类?_C#_.net_Reflection - Fatal编程技术网

C# 动态返回内部类?

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

在下面的代码中。函数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.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;
}