如何在运行时转换数据注释

本文关键字:数据 注释 转换 运行时 | 更新日期: 2023-09-27 18:22:09

在C#中,DataAnnotations允许您指定类、方法或属性的一些属性。

我的问题是幕后到底发生了什么?它是利用decorator模式将类包装到另一个也包含额外行为(例如字符串的长度、数字的范围等)的类中,还是以完全不同的方式发生?

如何在运行时转换数据注释

数据注释是属性。属性在运行时通过反射检索。看看这篇文章。

属性教程

除了Dan的答案,理解它们的最好方法是创建一个。。。

void Main()
{
    Console.WriteLine (Foo.Bar.GetAttribute<ExampleAttribute>().Name);
    // Outputs > random name
}
public enum Foo
{
    [Example("random name")]
    Bar
}
[AttributeUsage(AttributeTargets.All)]
public class ExampleAttribute : Attribute
{
    public ExampleAttribute(string name)
    {
        this.Name = name;
    }
    public string Name { get; set; }
}
public static class Extensions
{
    public static TAttribute GetAttribute<TAttribute>(this Enum enumValue)
            where TAttribute : Attribute
    {
        return enumValue.GetType()
                        .GetMember(enumValue.ToString())
                        .First()
                        .GetCustomAttribute<TAttribute>();
    }
}
// Define other methods and classes here