C#属性必需属性

我已经创建了属性

[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] [Serializable] public class TestPropertyAttribute : System.Attribute { public string Name { get { return _name; } set { _name = value; } }string _name; } 

我应该将“名称”标记为此属性的强制属性。 怎么做?

将它放在构造函数中而不是作为单独的属性:

 [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; } } } 

我不相信你可以强制它, 在应用属性时使用Name=...语法。

您应该使用System.ComponentModel.Data.Annotations.StringLength(dot.NET 4)属性来强制字符串的最小长度,并在您的数据中进行validation。 此外,(并且人们会因为它通常是糟糕的设计而嘲笑我)当我没有填充名称时,我会从ctor抛出一个InvalidDataException(“你必须在属性中输入一个名字”)。

我之所以使用这个是因为这是一个设计时属性,并且该exception将在应用程序启动时运行,因此对于开发人员来说更容易修复,这不是最佳选择,但我不知道如何与设计师沟通。

我一直在寻找与ErrorList中的警告/错误直接通信的方法,但直到现在我还没有找到一种简单的方法来做到这一点,除了构建我自己的自定义设计器或插件。 我已经想过很多关于构建一个可以寻找SendWarning,SendError,自定义属性的插件,但还没有实现它。

就像我说的

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