Can't read a const in a class instance?

后端 未结 3 1428
忘了有多久
忘了有多久 2021-01-01 10:55

I was mildly surprised when the compiler complained about this:

public class UsefulClass
{
    public const String RatingName = @\"Ratings\\rating\";
}

publ         


        
相关标签:
3条回答
  • 2021-01-01 11:33

    Because constants just aren't instance members; they're statically bound to their respective types. In the same way you can't invoke static methods using instances, you can't access class constants using instances.

    If you need to get a constant off an instance without knowing its type first-hand, I suppose you could do it with reflection based on its type.

    If you're trying to add a member that can't be modified but pertains to instances, you probably want read-only fields or properties instead.

    0 讨论(0)
  • 2021-01-01 11:39

    Because const in c# are implicitly of static type. And As static members can be accessed only on class member and not on instance, const cannot too.

    0 讨论(0)
  • 2021-01-01 11:42

    A "variable" marked const is a compile time construct, not an instance member. You can access it like you would a static variable:

    public void SomeFunc()
    {
        UsefulClass useful = new UsefulClass();
        String rating = UsefulClass.RatingName; // Access as if static
    }
    

    That being said, I would personally wrap this into a property if it's meant to be used as you described, like so:

    public class UsefulClass
    {
        private const string ratingName = @"Ratings\rating";
    
        public string RatingName { get { return ratingName; } }
    }
    

    This would make your syntax work, but also be a better design, IMO, since it doesn't expose your constants publically.

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