相关疑难解决方法(0)

如何从泛型类或方法的成员中获取T的类型?

假设我在类或方法中有一个泛型成员,所以:

public class Foo<T>
{
    public List<T> Bar { get; set; }

    public void Baz()
    {
        // get type of T
    }   
}
Run Code Online (Sandbox Code Playgroud)

当我实例化类时,T变为MyTypeObject1,所以类具有通用列表属性:List<MyTypeObject1>.这同样适用于非泛型类中的泛型方法:

public class Foo
{
    public void Bar<T>()
    {
        var baz = new List<T>();

        // get type of T
    }
}
Run Code Online (Sandbox Code Playgroud)

我想知道,我的类列表包含什么类型的对象.所以调用的list属性Bar或局部变量baz包含什么类型的T

我做不到Bar[0].GetType(),因为列表可能包含零元素.我该怎么做?

.net c# generics

647
推荐指数
11
解决办法
60万
查看次数

如何从字符串表示中获取泛型类型?

我有MyClass<T>.

然后我有了这个string s = "MyClass<AnotherClass>";.如何从字符串中获取Type s

一种方法(丑陋)是解析"<"和">"并执行:

Type acType = Type.GetType("AnotherClass");  
Type whatIwant = typeof (MyClass<>).MakeGenericType(acType);
Run Code Online (Sandbox Code Playgroud)

但有没有更简洁的方法来获得最终类型,没有任何解析等?

c# reflection types

79
推荐指数
3
解决办法
9万
查看次数

标签 统计

c# ×2

.net ×1

generics ×1

reflection ×1

types ×1