我需要定义一些将由基类及其子类使用的常量 . 不确定定义它们的正确方法是什么 .
我理解const,readonly,static const以及public,protected和private之间的区别(虽然我很少看到C#中使用了“protected”) . 应该如何定义这些常量?它们应该是公共const,公共只读,私有常量还是私有只读,并使用公共getter / setter来使用子类,还是应该将它们定义为受保护?
另一个问题是关于BaseClass中的变量FilePath . FilePath将被BaseClass中的某些函数用作占位符(实际值将由子类提供),我应该将其定义为虚拟吗?
有人可以提供一般规则吗?以下是我所拥有的一个例子:
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
}
}
}