我有一个抽象类,其中包含依赖于类级变量的方法。但是,这些变量的值是在从抽象继承的类中设置的。
我写这个是为了在构造函数中设置变量——这似乎是迄今为止最巧妙的事情。但我对此隐约感到不舒服——它们看起来应该是抽象属性。我只是想不通为什么会有这种感觉。
这是我实际所做的一个简化示例:
public abstract class TestBase
{
protected string itemType;
}
public class TestClass1 : TestBase
{
public TestClass1()
{
itemType = ConfigurationManager.AppSettings["TestClass1.ItemType"];
}
}
public class TestClass2 : TestBase
{
public TestClass2()
{
itemType = ConfigurationManager.AppSettings["TestClass2.ItemType"];
}
}
所以,问题是:
1) 这是不好的做法吗?
2) 如果是这样,为什么,什么更好?
3) 这是一个测试类,用于回归测试而不是部署到任何地方。是否有充分的理由像示例中那样在配置中设置我的类级变量,或者可以对它们进行硬编码吗?默认情况下,我总是倾向于配置。
干杯, 马特
最佳答案
您可以将数据传递给正确的构造函数:
public abstract class TestBase
{
protected string itemType; // can now become 'readonly`
protected TestBase(string keyName)
{
itemType = ConfigurationManager.AppSettings[keyName];
}
}
public class TestClass1 : TestBase
{
public TestClass1() : base("TestClass1.ItemType")
{
//itemType = ConfigurationManager.AppSettings["TestClass1.ItemType"];
}
}
这样它会更加一致并且不会那么容易忘记一个项目。
关于c# - 最佳实践 - 在派生类中设置继承变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16058356/