类型参数的约束 - 根据类型从字典中获取值

时间:2011-03-10 15:12:58

标签: c# generics constraints

代码:

private static Dictionary<Type, IObserverComponent> _components;
public static T Get<T>()
        where T : Type
    {
        return _components[T] as T;
    }

我该如何做到这一点?它说:'T'是'类型参数',但用作'变量'

2 个答案:

答案 0 :(得分:3)

您需要使用typeof(T)才能使其正常工作。

public static T Get<T>()  where T : Type
{
    return _components[typeof(T)] as T;
} 

答案 1 :(得分:1)

_component[someKey]会返回IObserverComponent,那么你怎么能让你的方法返回T?

你的方法不应该是这样的吗?

public static IObserverComponent Get<T>()
        where T : Type
{
    return _components[typeof(T)];
}