c# - 我可以使用 C# 方法(带参数)的结果作为另一个方法的默认参数吗?

标签 c# static-methods

我有一个带有方法的静态类:

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/

相关文章:

c# - 如果路径包含 "#",则 System.Uri 无法提供正确的 AbsolutePath 和 LocalPath

java - 有没有办法将包私有(private)类传递给静态方法

c# - 如何获取项目文件夹中文件的相对路径?

c# - 如何在asp.net web api中检测操作系统、浏览器、设备名称等设备信息?

generics - 从dart中的静态函数访问类中的类型参数的解决方法

java - Google Go 中抽象类/方法 (Java) 的等价性

mocking - 模拟静态函数调用时出错

java - 为什么 Java 不允许重写静态方法?

c# - 在不同文化中格式化数字

c# - 数据访问层的设计模式