2012-03-27 56 views
1

我想調用一個方法,該方法需要基於之前選擇的參數的一些參數。基於其他參數的必需參數

這可能是更好的用一個例子解釋:

public static void MyMethod (string p1, string p2, string p3 = "", string p4 = "") 
{ 
} 

我想實現的是需要p4如果p3給出。

如果我這樣稱呼它:

MyMethod("Hello", "World", "P3", // p4 now required as p3 given a value) 

我希望這是有道理的。謝謝。

回答

10

取而代之的參數的缺省值(它有其自身的問題),我會用超載:

public static void MyMethod (string p1, string p2) 
{ 
    MyMethod(p1, p2, "", ""); 
} 

public static void MyMethod (string p1, string p2, string p3, string p4) 
{ 
    ... 
} 
+0

謝謝,這幫助我做我所需要的。 +1 – 2012-03-27 11:20:24

1

你可以做什麼@Aliostad建議,這是有道理的,如果這是你的唯一要求。如果不是這樣,我想你最好把方法分成幾個方法,用不同的名字,這樣調用你方法的人不會太困惑。

1

上面的解釋可能足以解決您的問題。下面提到您可以在超載方法中編寫的代碼。

public static void MyMethod (string p1, string p2) 
{ 
    MyMthod(p1, p2, "", ""); 
} 

public static void MyMethod (string p1, string p2, string p3, string p4) 
{ 
    if(p3 has a value but p4 is missing the value) 
    throw new Exception("p4 is required"); 

} 
+0

是不是很難在c#中編寫它? 「p3有一個值,但p4缺少值」 – sasjaq 2012-03-27 11:32:24

+0

抱歉,我認爲它非常簡單,並忽略了相同。 – Shailesh 2012-03-27 12:02:33