简体   繁体   中英

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() .

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

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 technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM