加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 00:21:52 所属栏目:百科 来源:网络整理
导读:我有一个方法的静态类: 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
我有一个方法的静态类:

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[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’的默认参数值必须是编译时常量”,这是上述的较短版本.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读