【问题标题】:Provide default value for a parameter of 'Type' causes "Error CS1736 Default parameter value for 'eType' must be a compile-time constant"为 'Type' 的参数提供默认值会导致“错误 CS1736 'eType' 的默认参数值必须是编译时常量”
【发布时间】:2019-08-25 06:54:01
【问题描述】:

在 C# 中,我们可以提供参数的默认值,如下所示:

void Foo(int i = 0) {}

但是当我们传递Type的默认参数时:

void FooWithTypeParam(Type eType = typeof(double)) {}

导致

Error CS1736 Default parameter value for 'eType' must be a compile-time constant

我发现here 可以使用空值来提供内部默认值。

目前的解决方案是:

void FooWithTypeParam(Type eType = null)
{
   eType = eType ?? typeof(decimal);
}

但是用户看不到默认值是什么! 请问您有什么建议吗?

【问题讨论】:

  • 目前还不清楚您想要什么样的建议,恐怕。您不能使用非空 Type 引用作为默认值,因为它不能是编译时间常数。您需要决定是否要 a) 完全没有默认值; b)使用重载来伪造默认值; c) 使用 null 作为默认值并记录其含义。
  • 两种方法(一种带参数,一种不带参数)——都带有适当的 XML 文档——可能是你最好的选择。

标签: c# c#-4.0 parameters


【解决方案1】:

好的。我想我知道你想要什么。您想要在编译时定义类型的东西,但您希望它是用户可调整的。 它被称为“泛型”。非常适合这个;)

public interface Foo<T, U> {
    void foobar (T first, U second);
}

public class Bar implements Foo {
    void foobar (T first, U second) {
        //Stuff
    }
}

//Use this like....
Bar bar = new Bar<Double, Decimal>

现在对于函数的默认值,您可以使用 null 而不必担心正确的类型显示。函数参数将显示您在创建对象时为 U 和 T 输入的内容。它还在编译期间进行类型验证 - 不要激动死:)

还有一个链接供参考。 https://www.tutorialsteacher.com/csharp/csharp-generics

【讨论】:

    【解决方案2】:

    我只能这样做:

    public MyMethod(int a, Type typeParam = null)
    {
         // Set typeParam with default value "int" if is null:
         if(typeParam == null)
            typeParam = typeof(int);
    ......
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-07-07
      • 2019-07-04
      • 1970-01-01
      • 2020-09-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多