2013-10-09 63 views
1

我是.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 <>)做出錯誤編譯像

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

我肯定少不了的東西,你能不能幫我創建我的實例?

回答

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

謝謝你,這是完美的工作吧! – Lumy