数据注释在运行时如何转换?
How are data annotations transformed at runtime?
在 C# 中,DataAnnotations 允许您在 classes、方法或属性上指定一些属性。
我的问题是幕后到底发生了什么?它是利用装饰器模式并将 class 包装到另一个 class 中,该 class 还包含额外的行为(例如字符串的长度,数字的范围等),或者它发生在完全不同的地方方式?
数据注释是属性。通过反射在 运行 时间检索属性。看看这篇文章。
除了 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
在 C# 中,DataAnnotations 允许您在 classes、方法或属性上指定一些属性。
我的问题是幕后到底发生了什么?它是利用装饰器模式并将 class 包装到另一个 class 中,该 class 还包含额外的行为(例如字符串的长度,数字的范围等),或者它发生在完全不同的地方方式?
数据注释是属性。通过反射在 运行 时间检索属性。看看这篇文章。
除了 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