【发布时间】:2013-01-09 22:39:16
【问题描述】:
这应该很容易回答,但我什至不知道如何正确地问它,所以我提前为我的 n00b-ness 道歉。对于没有运气的搜索,我一直在努力解释它......
基本上我有一个方法,它接受几个参数作为“开关”(由调用方法设置为 0 或 1)和可选字符串,并使用它们来“构建”其行动计划。它是这样的:
public static void Foo(int a, int b, int c, optionalString aa, optionalString, bb, optionalString cc)
{
if (a == 1)
{ Object1 o1 = Thing.Property1[aa]; }
if (b == 1)
{ Object2 o2 = Thing.Property2[bb]; }
if (c == 1)
{ Object3 o3 = Thing.Property3[cc]; }
Bar(optionalo1, optionalo2, optionalo3); // Edit: I explained this part a little wrong, see below.
}
编辑澄清:我不能将空值传递给Bar(),因为它只需要使用实际设置的属性来调用。例如,调用 Foo() 时设置的 a、b 和 c 如下所示:
Foo(1, 0, 1, string1, string3) //In this instance I only want the first and third properties set. The strings contain the values I want them set to.
{
if (a == 1)
{ set this property based on string1 }
if (b == 1)
{ this one would not be set because b was 0 }
if (c == 1)
{ set this property based on string3 }
Bar(property1, property3);
// In this instance, Bar() must be called with only those two arguments, it cannot contain any null values.
编辑结束
所以,如果不对Bar() 的每个可能组合使用大量嵌套的if() 语句或方法,有没有办法在所有这些都被评估后调用它?从技术上讲,尚未分配变量,因此Bar() 无效。或者,有没有更好的方法来完成这样的事情?
这适用于与 SharePoint 服务器对象模型交互的控制台应用程序,如果这有什么不同的话。非常感谢您的宝贵时间!
【问题讨论】:
-
首先,一个可以为 0 或 1 的“开关”不是 int,它是
bool。 -
另外,那些字符串参数在严格意义上不是可选的,为什么不直接使用
string aa == null,如果它的null 不使用呢? -
你的问题很难理解。似乎除了您在示例代码中遇到的一些奇怪的命名问题外,它完全符合您的要求。
-
贴一些相关代码,看到IFoo, Foo & Bar 感觉像个外星人
-
你不能用泛型解决这个问题吗?
标签: c# methods sharepoint-2010 optional-arguments