기본 클래스와 하위 클래스에서 사용할 상수를 정의해야합니다. 올바른 정의 방법이 무엇인지 알 수 없습니다.하위 클래스에서도 사용되는 상수를 정의하는 방법은 무엇입니까?
나는 const, readonly, static const와 public, protected, private의 차이점을 알고 있습니다. (C#에서는 "protected"가 거의 사용되지 않습니다.) 이 상수는 어떻게 정의되어야 하는가? 그것들은 public const, public readonly, private constant 또는 private readonly이어야하며, 서브 클래스에 대한 public 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
}
}
}
실제로 사용하지 않는 기본 클래스 대신 상수를 실제로 사용하는 하위 클래스를 선언하지 않으시겠습니까? – Krease
또한'public const string Address = City + ","+ State + ","+ Country "를 사용할 수도 있습니다. –
@Chris이 상수는 둘 이상의 하위 클래스에서 사용될 것입니다. 나는 그들을 여러 번 정의하고 싶지 않다. – ericyoung