[英]C# static objects with shared interface - is this viable?
我幾乎可以肯定我想做的事情是不可能的,但是我希望我錯過了本書中的一個竅門。
我正在做一個對象可以具有多種屬性的項目。 每個屬性可以具有一組不同的值。 現在,這些屬性和值是使用內部Dictionary<string, string>
(我對此無能為力)和硬編碼魔術查找字符串引用的。
if (dog.attribute("color") == "black" || dog.attribute("color") == "brown") {
//...
}
自然,隨着屬性和值的數量增加並變得越來越復雜,這會引起問題。 我想把它變成基於對象的東西,所以我可以將屬性名稱和有效值分組。 枚舉聽起來很完美,但是在所有屬性名稱和值上鍵入的字符串都打破了這個主意。 我想到了字符串常量:
public class Color {
public const string AttributeName = "color";
public const string DefaultValue = Black;
public const string Black = "black";
public const string Brown = "brown";
}
//...
if (dog.attribute(Color.AttributeName) == Color.Black || dog.attribute(Color.AttributeName) == Color.Brown) {
//...
}
這對於維護來說更好,但是仍然很丑陋,而且我無法強制AttributeName
和DefaultValue
常量的存在。 我想到了繼承的屬性:
public abstract class DogAttribute {
public abstract string AttributeName { get; }
public abstract string DefaultValue { get; }
}
public class DogColor : DogAttribute {
public override string AttributeName => "color";
public override string DefaultValue => Black;
public string Black => "black";
public string Brown => "brown";
}
但是現在我犧牲了靜態引用屬性的能力。
//really really bad
if (dog.attribute(new DogColor().AttributeName) == new DogColor().Black || dog.attribute(new DogColor().AttributeName) == new DogColor().Brown) {
//...
}
//better, but still really bad given how heavily attributes are used
DogColor dogColor = new DogColor();
if (dog.attribute(dogColor.AttributeName) == dogColor.Black || dog.attribute(dogColor.AttributeName) == dogColor.Brown) {
//...
}
我99%確信,要靜態地引用這些屬性對象並希望這些屬性對象具有某種標准接口的組合是不可能的。 我是否缺少有效的實現選項,或者缺少某種不太完善的重構字符串湯的方法? (我懷疑這很重要,但是使用反射是不可行的。重構必須保持性能不變。)
我認為單例是一個不錯的選擇:
public class DogColor : DogAttribute {
public static DogAttribute Instance;
public override string AttributeName => "color";
public override string DefaultValue => Black;
public string Black => "black";
public string Brown => "brown";
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.