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

标签 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 是一个接口(interface),Type 是实现Feed 接口(interface)的类的类型。 GetInstance() 是这些类中的静态方法。 typeof(T).GetInstance(); 有问题吗?它说 System.Type 不包含 GetInstance() 的定义。

最佳答案

你可以像这样使用反射来调用静态方法:

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

关于c# 对静态函数的泛型方法调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4506396/

相关文章:

java - 递增和递减静态变量不显示更新值

c# - 通过 C# 获取网络接口(interface)类型

c# - 通用查找函数作为参数

generics - 如何将某种通用闭包传递给函数以生成特定值

c - 动态数组和预建数据

android - Android 中保存静态变量的 "Globals"类是否安全?

c# - CaSTLe Windsor 3.1 缺少方法异常

c# - 无法在面向 .NET 3.5 的 Visual Studio 2012 中的 C# 项目中使用 CLI 类库中的 CLR 类型并使用 Windows7.1SDK 工具集进行编译

c# - 为什么我的 ValidationMessageFor For TextArea 在页面加载时显示

c# - 从枚举中获取值到通用列表中