我在一个类中有一个泛型方法如下
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)];
}
}
