简体   繁体   中英

Why can't I access a public const in c#?

I have something like this:

namespace MyNamespace {    

    public partial class MyClass: UserControl {

        public static const String MYCONST = "MyConstant";

I can't see MYCONST from anywhere even from MyClass, why ?

A constant is available in a static context anyway, so remove the static keyword and you'll be fine.

MSDN docs:

The static modifier is not allowed in a constant declaration.

The reason is that a constant's value has to be fully evaluated at compile time and what the compiler does is that it takes that value and replaces all the usages of the constant throughout the code with the constant value.

That is why it sometimes can be better to use a public readonly value instead as the compiler does not replace the usages with the value but instead links to the readonly variable. This is especially something to think about when using constants from another assembly since you might not update all assemblies at once and you might end up with assmblies using the old constant value.

Ref: http://msdn.microsoft.com/en-us/library/e6w8fe1b(v=vs.80).aspx

According to the documentation for const

The static modifier is not allowed in a constant declaration.

Remove the static keyword from your constant and it should work.

Edit
Note that a const will be available as a class member, just like when you have static for non const variables. But for const the static is implicit and not allowed to type out.

What the heck kind of compiler are you using?

In general, making constants public is not a good idea. They behave differently from readonly variables, their literal value gets compiled into the IL. Which is a problem if the const is declared in another assembly. You could, say, ship a bug fix for an assembly that modified the const value. The other assemblies in your product will however continue to use the old value. The jitter won't complain about the mismatch. Not good.

A public const is only okay if it is a 'manifest' constant. Like Math.PI, only running the code in another universe could produce unexpected results. A product or company name is already pretty risky.

它应该可以作为MyNamespace.MyClass.MYCONST访问

You have a compile error in your code.

When I compile your code I get this:

The constant 'MyNamespace.MyClass.MYCONST' cannot be marked static

See the motivation for this error on Eric Lippert's blog:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM