Why it is not allowed to create datetime constant in .net?

前端 未结 2 347
甜味超标
甜味超标 2021-01-03 19:10

I want to create a datetime constant in .net but getting the error message

const DateTime dt = Convert.ToDateTime(\"02/02/2014\");

\'System

相关标签:
2条回答
  • 2021-01-03 19:56

    Even if you could declare a DateTime as const (which you can't, as other answers have indicated) you would have to use a compile-time constant as the value - and DateTime.Now most certainly isn't a compile-time constant.

    This is valid though:

    static readonly DateTime dt = DateTime.Now();
    

    Note that this will be "whatever time the type initializer for the type ran" though. That's rarely a particularly useful value unless you ensure it's initialized on start-up, assuming that's what you're trying to measure...

    0 讨论(0)
  • 2021-01-03 20:01

    DateTime is not a native type in the C# language - it's a struct from the .Net libraries.

    In C#, you can only create consts from the native language types, and you can only initialise them with values that can be calculated at compile-time. DateTime.Now cannot be calculated at compile time.

    (The only reference type you can use with a const is a string, and that's because strings are handled specially.)

    See http://msdn.microsoft.com/en-gb/library/e6w8fe1b%28v=vs.71%29.aspx

    0 讨论(0)
提交回复
热议问题