Can't read a const in a class instance?

后端 未结 3 1506
忘了有多久
忘了有多久 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: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.

提交回复
热议问题