是否有可能有一个类型独立的属性类,可能用“where or”约束装饰?
例子:
public class Attribute<T> where T: string || bool {
public const char ATTRIBUTE_CHAR = 'a';
public string Key { get; set; }
public T Value { get; set; }
public Attribute(string key, T value) {
Key = key;
Value = value;
}
public Attribute(string key, bool value = true)
: base(key, value) {}
public Attribute(string key, string value)
: base(key, value) {}
public override string ToString() {
if(typeof(value) == bool && (bool)value)
return String.Format({0}={1},
ATTRIBUTE_CHAR, key);
else return String.Format({0}={1}:{2},
ATTRIBUTE_CHAR, key, (string)value);
}
}
这样:
Attribute<bool> BoolAttr1 = new Attribute<bool>("bool_1");
Attribute<bool> BoolAttr2 = new Attribute<bool>("bool_2", false);
Attribute<string> StringAttr1 = new Attribute<string>("string_1", "val1");
Attribute<string> StringAttr2 = new Attribute<string>("string_2", "val2");
...everything.ToString();
将产生以下输出
a=bool_1
a=string_1:val1
a=string_2:val2
但这样的事情永远不可能:
Attribute<int>...