【问题标题】:Generic type attribute with OR constraint具有 OR 约束的泛型类型属性
【发布时间】:2013-07-22 10:53:15
【问题描述】:

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

【问题讨论】:

  • 能否说明属性类的用途?
  • @daryal 在库中解析和提供类似的东西:a=recvonly CRLF a=rtpmap:99 h263-1998/90000 这里有 2 种类型的属性,一种是布尔型(只有一个“启用”属性的键,如果它是false 它不会出现在消息中),一个是字符串(键 'rtpmap' 和值 '99 h263...)
  • 为什么需要泛型?你的Attribute&lt;T&gt; 类中没有任何共同的逻辑。泛型的全部意义在于以相同的方式对待不同类型的对象。如果您需要诸如if (typeof(T) == bool) 之类的行,那么这是一个信号,表明您做错了。并回答您的问题 - 不,没有or
  • @NikitaBrizhak Uff,感谢您为我解惑。您介意发表您的评论作为答案,以便我可以上船/接受吗?

标签: c# .net generics


【解决方案1】:

没有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;
   }
}

【讨论】:

    【解决方案2】:

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

    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() 等)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-06-05
      • 2021-01-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-05
      • 1970-01-01
      相关资源
      最近更新 更多