2017-01-03 25 views
0

我試圖在函數和動作上使用Convert方法,所以我可以避免編寫重複方法在Func類型的委託中進行。轉換方法來自Convert Action<T> to Action<object>動態地將Func轉換爲相應的動作

public class Program 
{ 
    static void Main(string[] args) 
    { 
     var program = new Program(); 
     var mi = program.GetType().GetMethod("Function", BindingFlags.Instance | BindingFlags.Public); 
     // Can be any version of Func 
     var funcType = typeof(Func<int, int>); 
     // Create action delegate somehow instead 
     var del = mi.CreateDelegate(funcType, null); 
     // Or dynamically convert the Func to a corresponding Action type (in this case Action<int>) 
    } 

    // Or find a way to pass it in as a parameter here 
    public Action<object> Convert<T>(Action<T> action) 
    { 
     return o => action((T)o); 
    } 

    public int Function(int five) 
    { 
     return five; 
    } 
} 
+0

你的代碼有什麼問題?它是否按照您期望的方式工作? – dasblinkenlight

+0

操作沒有返回類型 –

+0

我的代碼沒有問題,它的寫法是爲了提高理解力。我只是想動態地將一個Func變量轉換爲相應的Action變量。 – Martin

回答

0

我認爲你正在尋找的東西是這樣的:

public static Action<T1> IgnoreResult<T1,T2>(Func<T1,T2> func) 
{ 
    return x => func(x); 
} 

但對於Func<T1,T2....>

所有變體,我認爲這會工作:

public static Action<TR> IgnoreResult<TR>(Delegate f) 
{ 
    return x => f.DynamicInvoke(x); 
} 

用途:

var action = IgnoreResult<int>(new Func<int,int>(program.Function)); 
action(5); 

你無法得到它推斷出參數的不復制返回類型和粘貼爲Action<T1...>Func<T1,T2...>所有變體的第一個例子。

+0

1.解決方案:正如我在我的問題中提到的,我的目標是隻有一個可以調用Action和Func的方法,這會將我們引導到 2.解決方案:您創建一個調用DynamicInvoke的委託,該委託的速度慢30倍比直接調用。 – Martin

+0

對,所以你想兩全其美=)這可以做到但是很快,我會回覆你 – Stuart

+0

我應該告訴你,你不能使用動態關鍵字或表達式樹。 Unity不支持動態表達式樹,並且僅支持V5.5.0及更高版本.LambdaExpression.Compile的性能如此糟糕,您必須調用委託數百萬次才能獲得初始化成本。 – Martin