2013-04-18 17 views
1

我有以下功能:C#:將一個通用的功能函數求對象

private int GetEnumTypeUnderlyingId<T>() 
     { 
      return (int)Enum.Parse(typeof(T), Enum.GetName(typeof(T), _franchise.LogonDialog)); 
     } 

我想將其轉換爲Func type。我寫了這樣的:

Func<int> GetEnumTypeUnderlyingIdFunc<T> =() => (int)Enum.Parse(typeof(T), Enum.GetName(typeof(T), _franchise.LogonDialog)); 

但這不起作用。在使用Func <>,泛型和lambda表達式時,我不是很舒服,因此任何幫助都將不勝感激

+0

它不會這樣工作,因爲C#不支持通用屬性 –

回答

2

您可以定義自己的委託。這裏是你正在尋找的:

//Your function type 
delegate int GetEnumTypeUnderlyingIdFunc<T>(); 

//An instance of your function type 
GetEnumTypeUnderlyingIdFunc<int> myFunction =() => //some code to return an int ; 

此外,這也行得通。

//An instance of Func delegate 
Func<int> GetEnumTypeUnderlyingIdFunc =() => //some code to return an int; 
+0

Lambda表達式仍取決於'T'。我不確定是否使用'GetEnumTypeUnderlyingIdFunc '而不是'GetEnumTypeUnderlyingIdFunc '會起作用。 – Dirk

+0

@Dirk你可以嘗試確保它正在工作。 –

+0

事情是通過使用'GetEnumTypeUnderlyingIdFunc '你專門的原始泛型方法'GetEnumTypeUnderlyingId '。現在它只對'int'有效。 – Dirk

0

另一個解決方案是

public Func<int> GetTheFunc<T>(T val) 
{ 
    Func<int> func =() => (int)Enum.Parse(typeof(T),Enum.GetName(typeof(T),val)); 
    return func; 
} 

然後

var func = GetTheFunc<_franchise>(_franchise.LoginDialog); 

//Now you can use the func, pass it around or whatever.. 
var intValue = func(); 
相關問題