我创建了类似
的属性 [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
[Serializable]
public class TestPropertyAttribute : System.Attribute
{
public string Name
{
get { return _name; }
set { _name = value; }
}string _name;
}
我应该将“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) 属性来强制字符串的最小长度,并在数据中进行验证。另外,(人们会嘲笑我,因为这通常是糟糕的设计*)当名称未填写时,我会从构造函数中抛出 InvalidDataException(“您必须在属性中输入名称”)。
我使用它的原因是因为这是一个设计时属性,异常会在应用程序启动时运行,因此开发人员更容易修复,这不是最好的选择,但我不知道如何与设计师沟通。
我一直在寻找直接与错误列表中的警告/错误进行通信的方法,但到目前为止,除了构建我自己的自定义设计器或插件之外,我还没有找到一种简单的方法来做到这一点。我已经考虑了很多关于构建一个插件来查找 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;
}
Jon Skeet 接受的答案是一个很好的解决方案。但是,现在您可以使用更短的代码来编写此代码。它的工作原理是一样的:
public class TestPropertyAttribute : Attribute
{
public TestPropertyAttribute(string name)
{
Name = name;
}
public string Name { get; }
}
现在是 2024 年,所以让我们把它缩短一点:)
public class TestPropertyAttribute(string name) : Attribute
{
public string Name => name;
}