使用Generic Type创建动态结构

时间:2013-10-09 12:42:29

标签: c# .net generics

我是.net和C#的新手,我正在尝试创建一个MyStruct实例,而不知道之前的Type。 所以我的类在构造函数中收到3个类型,我需要用这种类型创建一个MyStruct实例。 我看了上网,看到了最后一部分,但我无法编译。

namespace IQUnionTag
{
    public class IQUnionTag
    {
        private struct MyStruct<A, B, C>
        {
            public A value1;
            public B value2;
            public C value3;
        }
        private object MyStructure;
        private Type a;
        private Type b;
        private Type c;
        public IQUnionTag(Type a, Type b, Type c)
        {
            this.a = a;
            this.b = b;
            this.c = c;
            int d = 2;
            var d1 = typeof (MyStruct<>); // Doesn't compile
            Type[] typeArgs = { a, b, c };
            var makeme = d1.MakeGenericType(typeArgs);
            object o = Activator.CreateInstance(makeme);
            Console.WriteLine(o);
        }
    }
}

我只想要像

这样的东西
Mystructure = new MyStruct<a,b,c> // this doesn't compile too

typeof(MyStruct&lt;&gt;)使错误编译如

Erreur Using the generic type 'IQUnionTag.IQUnionTag.MyStruct<A,B,C>' requires 3 type arguments

我当然错过了什么,你能帮我创建我的实例吗?

1 个答案:

答案 0 :(得分:3)

目前尚不清楚你的目的是什么,但你能做到:

public class IQUnionTag
{
    private struct MyStruct<A, B, C>
    {
        public A value1;
        public B value2;
        public C value3;
    }

    private object MyStructure;
    private Type a;
    private Type b;
    private Type c;
    public IQUnionTag(Type a, Type b, Type c)
    {
        this.a = a;
        this.b = b;
        this.c = c;
        int d = 2;
        var d1 = typeof(MyStruct<,,>); // this is the way to get type of MyStruct
        Type[] typeArgs = { a, b, c };
        var makeme = d1.MakeGenericType(typeArgs);
        object o = Activator.CreateInstance(makeme);
        Console.WriteLine(o);
    }
}