[英]Construct generic instance with a generic parameter and a normal parameter
我已經遵循了struct,我需要通過System.Reflection創建它的實例。 最大的問題是我有一個通用和非通用參數。 我必須使用System.Reflection,因為它將在T可以變化的循環中調用。 我看這個 ,但我unabled得到它與第二個參數(INT標簽)工作。 對不起,我不得不問這個基本問題。
struct pair<T>
{
public pair(T value,int tag)
{...}
}
所以我需要魔術:
object createPair(object o,int tag)
{
return *somemagic*
}
編輯:解決方案是將結構與第一個答案結合起來公開。 如果結構嵌套在通用結構中,則兩個答案都將引發ArgumentException,而與輸入無關。 很抱歉,您不知道嵌套的這種影響。
使用MakeGenericType方法使輸入類型通用:
object createPair(object obj,int tag) {
Type type = typeof(Pair<>);
Type genericType = type.MakeGenericType(obj.GetType());
return Activator.CreateInstance(genericType, obj, tag);
}
但是如果可能的話,我會使用泛型而不是反射。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.