2012-10-30 19 views
1

我有一個方法,我多次調用,但每次從不同的方法調用另一個不同的方法從內部調用。在c中使用函數/代表的不同方法#

public void MethodOne() 
{ 
//some stuff 

*MethodCall(); 

//some stuff 

} 

所以MethodOne被多次調用,用不同的*MethodCall()各一次。我正在試圖做的是這樣的:

public void MethodOne(Func<> MethodCall) 
{ 
//some stuff 

*MethodCall; 

//some stuff 

} 

但被調用的方法各有不同的返回類型和不同的參數。有沒有辦法使用Functors來做到這一點?如果不是,我會怎麼做呢?

謝謝!

+3

你確定C#中有'*'嗎?此外,你將如何調用一個需要參數的函數而不實際提供它們? – Vlad

+0

這聽起來像你正在嘗試創建一個SuperMethod。你可能會考慮多看看你的設計。如果方法具有不同的輸入*和*不同的輸出,則可能不應將它們組合在一起。 –

回答

1

您最好的選擇是使用非通用Action型(或MethodInvoker將是相同的),即

public void MethodOne(Action callback) 
{ 
    //some stuff 

    if(callback != null) callback(); 

    //some stuff 
} 

從這裏就可以通過調用者包裹它調用的任何方法,即

MethodOne(SimpleMethod); // SimpleMethod has no parameters and returns void 
MethodOne(() => MoreComplexMethod(1, "abc")); // this one returns void 
MethodOne(() => { MethodThatReturnsSomething(12); }); // anything you like 

+0

如何在這種情況下返回結果? –

+0

@CongLe:'int res = 0; MethodOne(()=> {res = MethodThatReturnsSomething(12);});' – Vlad

+0

這正是我需要的,謝謝! –

1

不能調用需要的參數沒有提供他們的功能,所以答案是「不,不可能的」

另外,也許你想以下幾點:

void MethodOne(Action a) 
{ 
    // some stuff 
    a(); 
    // some stuff 
} 

... // somewhere in the code 
MethodOne((Action)(() => { DoSomethingOther(1, 2, 3); })); 
MethodOne((Action)(() => { DoSomethingEvenDifferent(1, 2, 3, 4, 5); })); 
+0

在'有些東西'期間,OP從'計算參數'停止了什麼? –

+0

@Amit:基本上,函數的簽名:他不知道「a」在現實中是否有爭論。如果用戶只需要調用「某些東西」,他肯定不知道論據是什麼或者可能是什麼。 – Vlad

0

這基本上是不可能的。你可以做MethodOne通用的返回類型,並用它關閉了它的外塊,而不是參數拉姆達:

static void Main(string[] args) 
{ 
    int parameterSubst = 1; 
    int result = MethodOne<int>(() => parameterSubst); 
    string result2 = MethodOne<string>(() => 
    { 
     string s = parameterSubst.ToString(); 
     s += "foo"; 
     return s; 
    }); 
} 

static T MethodOne<T>(Func<T> function) 
{ 
    return function(); 
} 

正如你所看到的,parameterSubst在通過Func<T>被使用過,但不是作爲一個參數。

1

.Net中的每個代表都是從Delegate派生的類的實例。因此,如果您確實希望將「任意」代理傳遞給方法,您可以將其傳遞爲Delegate

要調用它,您需要使用它的DynamicInvoke方法。

public void MethodOne(Delegate MethodCall) 
{ 
//some stuff 

//Assuming you now have the required parameters 
//or add params object[] args to the signature of this method 
object res = MethodCall.DynamicInvoke(args); //args is object[] representing the parameters 

//some stuff 
} 

但這不是推薦的DynamicInvoke是緩慢的,它不提供任何編譯時的安全性。可能你應該重新審視你的設計。

相關問題