1

我是 .net 和 C# 的新手,我正在尝试创建 MyStruct 的一个实例,但之前不知道类型。所以我的类在构造函数中接收 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<>) make error compile like

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

我当然错过了一些东西,你能帮我创建我的实例吗?

4

1 回答 1

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);
    }
}
于 2013-10-09T13:00:33.460 回答