How to define the constants the used also by the subclass?

I need to define some constants that will be used by the base class and its sub class. Not sure what is the correct way to define them.

I understand the differences of const, readonly, static const, as well as public, protected, and private (while I seldom see "protected" is used in C#). How these constant should be defined? should them be public const, or public readonly, or private constant, or private readonly and use public getter/setter for subclass to use, or should them be defined as protected?

Another question is about the variable FilePath in the BaseClass. FilePath will be used by some functions in the BaseClass as placeholder (the real value will be provided by subclass), should I define it as virtual?

Could somebody provide general rules to follow? The following is an example of what I have:

public class BaseClass
{
    public const string Country = "USA";
    public const string State = "California";
    public const string City = "San Francisco";

    public virtual string FilePath
    {
        get
        {
            throw new NotImplementedException();
        }
         set
        {
            throw new NotImplementedException();
        }
    }
}

public class Class1 : BaseClass {

     public Class1() {
         FilPath = "C:test";
     }

     public string GetAddress() {
       return City + ", " + State + ", " + Country; 
     }

     public void CreateFile() {
       if (!Directory.Exist(FilePath)) {
            //create folder, etc 
        }
     }         
}

If you can define the constants as const then do so. If that is not possible, go with static readonly .

If the constants are to be used outside of the class then they need to be internal or public . If only the base class and its descendants are going to use them then make them protected .

If FilePath can be provided by subclasses, then it has to be virtual . If it must be provided by subclasses, it should be abstract .


I would make BaseClass an abstract class (see http://msdn.microsoft.com/en-us/library/sf985hc5(v=vs.71).aspx). As for const vs. static readonly, its mainly a matter of taste.

public abstract class BaseClass
{
    // ... constant definitions

    // Members that must be implemented by subclasses
    public abstract string FilePath { get; set; }
}
链接地址: http://www.djcxy.com/p/21082.html

上一篇: 为什么以及如何在C#中使用静态只读修饰符

下一篇: 如何定义由子类使用的常量?