开发者

c# Generic method call to static function

I have a generic method in a class as follows

    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)];          
        }
    }

Here, Feed is an interface and Type is of types of classes that implement the Feed interface. GetInstance() is a static method in these classes. Is there something wrong with typeof(T).GetInstance();? It says System.Type does not contain a definition for GetInstance().


You can use Reflection to call a static method like so:

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)];          
    }
}


The simplest way is to use the new constraint

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)];          
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜