【发布时间】:2011-11-05 08:43:31
【问题描述】:
不幸的是,我仍在使用 .NET 2.0。我之前没有创建自定义属性。
我想创建一个CustomStringFormatAttribute:。
如果一个类,比如 Customer.Name,有:
MaxLength=30
ActualLength=10
我需要用空格填充它直到达到 30。
我还需要一个可以像 DisplayDataFormat 这样格式化的日期属性
我已经创建了以下内容,但 如何访问属性中属性的实际值?
public class Customer
{
[CustomStringFormatAttribute(30)]
public string Name { get; set; }
//todo:customDateAttribute
public DateTime StartDate { get; set; }
}
[AttributeUsage(AttributeTargets.Property, Inherited = false, AllowMultiple = true)]
public sealed class CustomStringFormatAttribute : Attribute
{
private readonly int maxLength;
public CustomStringFormatAttribute(int maxLength)
{
MaxLength = maxLength;
}
public int MaxLength { get; private set; }
//?Should I override ToString
public override string ToString()
{
return Format();
}
private string Format()
{
//simplified version of my formatting for brevity
string source = "value from the property of the class.";//How do I get access to the actual value of the property within the attribute?
const char paddingChar = ' ';
return source.PadLeft(maxLength, paddingChar);
}
}
有什么建议吗?
注意:为简洁起见,我使用了自动属性。我在 .NET 2.0 中没有这种奢侈。
【问题讨论】:
-
不太清楚您要完成什么,但您可能不恰当地使用了属性。属性与类型相关联,而不是与该类型的对象相关联。如果您需要特定对象的自定义显示格式,那么您必须使用普通属性。
标签: c# .net .net-2.0 custom-attributes