简体   繁体   English

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

[英]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. 这里, Feed是一个接口, Type是实现Feed接口的类的类型。 GetInstance() is a static method in these classes. GetInstance()是这些类中的静态方法。 Is there something wrong with typeof(T).GetInstance(); typeof(T).GetInstance();是否有问题typeof(T).GetInstance(); ? It says System.Type does not contain a definition for GetInstance() . 它说System.Type不包含GetInstance()的定义。

The simplest way is to use the new constraint 最简单的方法是使用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)];          
    }
}

You can use Reflection to call a static method like so: 您可以使用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)];          
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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