简体   繁体   中英

Create dynamic struct with Generic Type

I'm new in .net and C# and I'm trying to create an instance of MyStruct, without known the Type before. so my class receive 3 type in the constructor and I need to create an Instance of MyStruct with this type. I looked on internet and saw the last part but I can't compile this.

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);
        }
    }
}

I just want something like

Mystructure = new MyStruct<a,b,c> // this doesn't compile too

typeof(MyStruct<>) make error compile like

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

i certainly missed something, can you help me to create my instance?

It is not clear what is your purpose but you can do:

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);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM