我有一个带有方法的静态类:
public static class FooUtilities
{
public static FooStruct[] GetFooBar(int foo)
{
var fooStruct = new FooStruct[];
// Connect to SOAP API, collect data to put in fooStruct
...
return fooStruct;
}
}
现在我想将 GetFooBar(int foo) 的结果用作另一个方法的参数,该方法使用此方法的结果创建新的 fooItem 项,例如:
public static FooItem CreateFooItem(fooResult = GetFooBar(int foo))
{
var fooItem = new FooItem(fooResult[0].value, fooResult[1].value,fooResult[2].value);
...
return fooItem;
}
我现在的做法是这样写:
public static FooItem CreateFooItem(FooStruct[] fooResult)
{
var fooItem = new FooItem(fooResult[0].value, fooResult[1].value,fooResult[2].value);
...
return fooItem;
}
这行得通,但我必须像这样调用方法:
FooItem myItem = FooUtilities.CreateFooItem(FooUtilities.GetFooBar(12321));
我想要的是能够调用:
FooItem myItem = FooUtilities.CreateFooItem();
并在调用此方法时隐式包含参数。
这可能吗?
最佳答案
你不能这样做。来自 the spec :
A default value must be one of the following types of expressions:
a constant expression;
an expression of the form new ValType(), where ValType is a value type, such as an enum or a struct;
an expression of the form default(ValType), where ValType is a value type.
如果您尝试了 CreateFooItem(fooResult = GetFooBar(int foo))
示例,您会遇到编译器错误“'fooResult' 的默认参数值必须是编译时constant”,这是上面的一个较短的版本。
关于c# - 我可以使用 C# 方法(带参数)的结果作为另一个方法的默认参数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13395492/