开发者

C# Attributes mandatory property

开发者 https://www.devze.com 2023-01-14 09:02 出处:网络
I\'ve created attribute like [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] [Serializable]

I've created attribute like

    [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
    [Serializable]
    public class TestPropertyAttribute : System.Attribute
    {
        public string Name
        {
            ge开发者_高级运维t { return _name; }
            set { _name = value; }
        }string _name;
    }

and I should mark "Name" as mandatory property of this attribute. How to do it?


Put it in the constructor instead of just as a separate property:

[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
[Serializable]
public class TestPropertyAttribute : System.Attribute
{
    readonly string _name;

    public TestPropertyAttribute(string name)
    {
        _name = name;
    }

    public string Name { get { return _name; } }
}

I don't believe you can make it mandatory and use the Name=... syntax when applying the attribute though.


You should use the System.ComponentModel.Data.Annotations.StringLength (dot.NET 4) attribute to force the min length of the string, and validate in your Data. Also, (and people will mock me for this as it's bad design usually*) i would throw an InvalidDataException("You must enter a Name in the attribute") from the ctor when Name is not filled.

The reason i would use this is because this is a design-time attribute and the exception would run as the app starts, so it would be easier to fix for the developer, this is not the best option, but I do not know how to communicate with the designer.

I have been looking on ways to communicate directly with the warnings/error in the ErrorList, but until now i have not found an easy way to do this, beside building my own custom designer or addin. I have thought alot about builing an addin that would look for an SendWarning, SendError , custom attributes, but have yet to make it happen.

as i said

 public sealed class TestPropertyAttribute : System.Attribute
{
    [System.ComponentModel.DataAnnotations.StringLength(50),Required]
    public string Name
    {
        get { return _name; }
        set
  { 
         if (String.IsNullOrEmpty(value)) throw new InvalidDataException("Name is a madatory property,  please fill it out not as null or string.Empty thanks"); }
       else
      _name= value;


  }
       string _name;
 }


The accepted answer by Jon Skeet is a good solution. However, you can write this with shorter code nowadays. It works the same:

public class TestPropertyAttribute : Attribute
{
    public TestPropertyAttribute(string name)
    {
        Name = name;
    }

    public string Name { get; }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消