默认参数和编译时间常量

时间:2021-03-26 10:56:01

Why is SqlInt32.Null not considered a compile-time constant? Because I cant use it as the default value of a default parameter.

为什么SqlInt32.Null不被视为编译时常量?因为我不能将它用作默认参数的默认值。

1 个解决方案

#1


5  

SqlInt32.Null is a static readonly field, not a constant. This means that its value may not be known at compile time.

SqlInt32.Null是静态只读字段,而不是常量。这意味着在编译时可能无法知道其值。

The main difference between a static readonly field and a const is that the const can be initialized only in the declaration of it, while the static readonly field can be initialized in the declaration or in a constructor.

静态只读字段和const之间的主要区别在于const只能在声明中初始化,而静态只读字段可以在声明或构造函数中初始化。

Example:

例:

public class SomeClass
{
    public static readonly int SomeValue;

    static SomeClass()
    {
        SomeValue = DateTime.Now.Millisecond;
    }
}

In the example above a static readonly field is initialized by the static constructor in a way that illuminates why it cannot be determined at compile time.

在上面的示例中,静态构造函数初始化静态只读字段,以阐明在编译时无法确定的原因。

#1


5  

SqlInt32.Null is a static readonly field, not a constant. This means that its value may not be known at compile time.

SqlInt32.Null是静态只读字段,而不是常量。这意味着在编译时可能无法知道其值。

The main difference between a static readonly field and a const is that the const can be initialized only in the declaration of it, while the static readonly field can be initialized in the declaration or in a constructor.

静态只读字段和const之间的主要区别在于const只能在声明中初始化,而静态只读字段可以在声明或构造函数中初始化。

Example:

例:

public class SomeClass
{
    public static readonly int SomeValue;

    static SomeClass()
    {
        SomeValue = DateTime.Now.Millisecond;
    }
}

In the example above a static readonly field is initialized by the static constructor in a way that illuminates why it cannot be determined at compile time.

在上面的示例中,静态构造函数初始化静态只读字段,以阐明在编译时无法确定的原因。