1

是否有可能有一个类型独立的属性类,可能用“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>...
4

2 回答 2

4

没有or。您可能想要做的是:

interface IKeyValue<TKey, TValue>
{
   public TKey Key {get;set;}
   public TValue Value {get;set;}
}

public class Attribute : IKeyValue<string, string>
{
   public override string ToString() 
   {
        return String.Format("{0}={1}:{2}", Constants.ATTRIBUTE_CHAR, Key, Value);
   }
}

public class BoolAttribute : IKeyValue<string, bool>
{
   public override string ToString() 
   {
        return Value ? String.Format("{0}={1}", Constants.ATTRIBUTE_CHAR, Key) : String.Empty;
   }
}
于 2013-07-22T11:46:21.137 回答
0

您可以创建抽象属性和所需的实现。然后可以以所需的方式处理每个属性。(转换为属性),但无法创建不受支持类型的属性。

public abstract class Attribute<T>
{
    public abstract T getValue();
}

public class StringAttribute : Attribute<String>
{
    String value;

    public String getValue(){
        return value;
    }

}

public class BooleanAttribute : Attribute<Boolean>
{
    Boolean value;

    public Boolean getValue()
    {
        return value;
    }
}

这也使您可以非常轻松地实现依赖于类型的属性函数。(如 toString() 等)

于 2013-07-22T12:17:46.257 回答