开发者

default parameters and compile time constants

开发者 https://www.devze.com 2022-12-16 23:57 出处:网络
Why is SqlInt32.Null not considered a compile-ti开发者_开发知识库me constant? Because I cant use it as the default value of a default parameter.SqlInt32.Null is a static readonly field, not a constant

Why is SqlInt32.Null not considered a compile-ti开发者_开发知识库me constant? Because I cant use it as the default value of a default parameter.


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

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.

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消