获取嵌套Generic的类型,创建该类型的新Object

时间:2016-11-29 17:11:45

标签: c# generics reflection casting

有没有很好的方法来实现以下目标?基本思想是有一个通用的方法,可以将List作为T,获取J的类型并在方法中创建一个新的List。并进一步创建J的实例。

仅生成

是不够的
Type t = typeof(T).GetGenericArguments().Single();


// I need this
public static void foo<T>(T obj)
{
    // For this specific Example T is List<nestedType>
    // Create new List of nestedType but nestedType may be any Class
    List<nestedType> = new List<nestedType>();
    nestedType o = new nestedType();
}

到目前为止我取得的成就

public static void foo<T>(T obj)
{
   var t = typeof(T); 
   if(t.GetInterfaces().Any(x => x.IsGenericType && x.GetGenericTypeDefinition() == typeof(IList<>)))
        {
            Type underlyingType = t.GetGenericArguments().Single();
            dynamic varOfUnderlyingType = Convert.ChangeType(??, underlyingType);
        }
}

0 个答案:

没有答案
相关问题