c#对静态函数的通用方法调用

时间:2010-12-22 05:20:37

标签: c# generics static

我在类中有一个泛型方法,如下所示

    private static Dictionary<Type, Feed> _singletons = new Dictionary<Type, Feed>();

    public static Feed GetFeed<T>() where T:Feed
    {    
        lock(_padlock)
        {
            if (!_singletons.ContainsKey(typeof(T))
            {                   
                _singletons[typeof(T)] = typeof(T).GetInstance();
            }
            return _singletons[typeof(T)];          
        }
    }

这里,Feed是一个接口,Type是实现Feed接口的类的类型。 GetInstance()是这些类中的静态方法。 typeof(T).GetInstance();有什么问题吗?它说System.Type不包含GetInstance()的定义。

2 个答案:

答案 0 :(得分:2)

最简单的方法是使用new约束

private static Dictionary<Type, Feed> _singletons = new Dictionary<Type, Feed>();

public static Feed GetFeed<T>() where T:Feed, new()
{    
    lock(_padlock)
    {
        if (!_singletons.ContainsKey(typeof(T))
        {                   
            _singletons[typeof(T)] = new T();
        }
        return _singletons[typeof(T)];          
    }
}

答案 1 :(得分:2)

您可以使用Reflection来调用静态方法,如下所示:

private static Dictionary<Type, Feed> _singletons = new Dictionary<Type, Feed>();

public static Feed GetFeed<T>() where T:Feed
{    
    lock(_padlock)
    {
        if (!_singletons.ContainsKey(typeof(T))
        {                   
            return typeof(T).GetMethod("GetInstance", System.Reflection.BindingFlags.Static).Invoke(null,null);

        }
        return _singletons[typeof(T)];          
    }
}
相关问题