经常写一些属性的时候都要判断属性的值是不是为空
比如
public string name
{
set{
   if(value==null)
   {//...}
   else name =value;
}
}
我现在不想写这些判断,不知道能不能这样[myAttribute("")]//指示此属性不能为空,为空就抛出异常
public string name
{
   set
   {
      name=value;
   }
}
请问大家这样做得到吗,具体怎么做??

解决方案 »

  1.   

    不能。但你可以使用snippet来简单你的代码输入的工作量。
      

  2.   

    Attribute不会对代码本身构成什么影响,而是其它程序在使用它时产生影响。
    比如:你可以这样写一个Attribute
    [NotNullProperty()]
    public string name{get;set;}然后当你在使用某一个类的某一个属性时先执行一次检查是否有这个Attribute.
     如果有,那么执行一次:
    if(valueString!=null)
        xxx.name = valueString;但你无法通过这个Attribute强制其它程序来执行这样的操作。
      

  3.   

            public string name
            {
                set
                {
                    if (string.IsNullOrEmpty(value))//or value==null
                    {
                        throw new NullReferenceException();
                    }
                    else
                    {
                        name = value;
                    }
                }
            }
      

  4.   

    “[]”本身没有任何意义的,就跟html标记中,你随便加些自定义的属性,然后自己再获取其值
      

  5.   

    我写了一个特性有个属性是DateTime类型的我要怎么调用啊
    MyAttribute["时间"]//参数类型是datetime的要怎么调用?
      

  6.   

    假设你的属性名称为:EditTime,
    你可以写:
    [My(EditTime = DateTime.Now)]
    也可以写成性:
    [MyAttribue(EditTime = DateTime.Now)]