2012-03-27 59 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