2010-12-22 138 views
1

我有一個類的一般方法如下C#泛型方法調用靜態函數

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是一個接口,Type是類型的實現Feed接口的類。 GetInstance()是這些類中的靜態方法。 typeof(T).GetInstance();有什麼問題嗎?它說System.Type不包含GetInstance()的定義。

+1

因爲`typeof運算()`返回`Type`對象。 'Type`類沒有這樣的方法。 – BoltClock 2010-12-22 05:24:17

+0

是的。我得到的那部分。那麼這個電話有什麼選擇? – Aks 2010-12-22 05:26:13

回答

2

您可以使用反射來調用像一個靜態方法,以便:

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

最簡單的方法是使用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)];   
    } 
}