[英]Create dynamic struct with Generic Type
我是.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
我當然錯過了什么,你能幫我創建我的實例嗎?
目前尚不清楚您的目的是什么,但您可以這樣做:
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);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.