Как получить аннотации данных из кода? (Программно)
Я использую System.ComponentModel.DataAnnotations
для обеспечения проверки моего проекта Entity Framework 4.1.
Например:
public class Player
{
[Required]
[MaxLength(30)]
[Display(Name = "Player Name")]
public string PlayerName { get; set; }
[MaxLength(100)]
[Display(Name = "Player Description")]
public string PlayerDescription{ get; set; }
}
Мне нужно получить значение аннотации Display.Name
, чтобы показать его в сообщении, например, "Имя игрока" - это Frank.
=============================================== ==================================
Еще один пример того, почему мне нужно было бы получить аннотации:
var playerNameTextBox = new TextBox();
playerNameTextBox.MaxLength = GetAnnotation(myPlayer.PlayerName, MaxLength);
Как я могу это сделать?
Ответы
Ответ 1
Метод расширения:
public static T GetAttributeFrom<T>(this object instance, string propertyName) where T : Attribute
{
var attrType = typeof(T);
var property = instance.GetType().GetProperty(propertyName);
return (T)property .GetCustomAttributes(attrType, false).First();
}
код:
var name = player.GetAttributeFrom<DisplayAttribute>("PlayerDescription").Name;
var maxLength = player.GetAttributeFrom<MaxLengthAttribute>("PlayerName").Length;
Ответ 2
попробуйте следующее:
((DisplayAttribute)
(myPlayer
.GetType()
.GetProperty("PlayerName")
.GetCustomAttributes(typeof(DisplayAttribute),true)[0])).Name;
Ответ 3
Вот несколько статических методов, которые вы можете использовать для получения MaxLength или любого другого атрибута.
using System;
using System.Linq;
using System.Reflection;
using System.ComponentModel.DataAnnotations;
using System.Linq.Expressions;
public static class AttributeHelpers {
public static Int32 GetMaxLength<T>(Expression<Func<T,string>> propertyExpression) {
return GetPropertyAttributeValue<T,string,MaxLengthAttribute,Int32>(propertyExpression,attr => attr.Length);
}
//Optional Extension method
public static Int32 GetMaxLength<T>(this T instance,Expression<Func<T,string>> propertyExpression) {
return GetMaxLength<T>(propertyExpression);
}
//Required generic method to get any property attribute from any class
public static TValue GetPropertyAttributeValue<T, TOut, TAttribute, TValue>(Expression<Func<T,TOut>> propertyExpression,Func<TAttribute,TValue> valueSelector) where TAttribute : Attribute {
var expression = (MemberExpression)propertyExpression.Body;
var propertyInfo = (PropertyInfo)expression.Member;
var attr = propertyInfo.GetCustomAttributes(typeof(TAttribute),true).FirstOrDefault() as TAttribute;
if (attr==null) {
throw new MissingMemberException(typeof(T).Name+"."+propertyInfo.Name,typeof(TAttribute).Name);
}
return valueSelector(attr);
}
}
Использование статического метода...
var length = AttributeHelpers.GetMaxLength<Player>(x => x.PlayerName);
Или используя дополнительный метод расширения для экземпляра...
var player = new Player();
var length = player.GetMaxLength(x => x.PlayerName);
Или используя полный статический метод для любого другого атрибута (например, StringLength)...
var length = AttributeHelpers.GetPropertyAttributeValue<Player,string,StringLengthAttribute,Int32>(prop => prop.PlayerName,attr => attr.MaximumLength);
Вдохновленный ответом здесь...
fooobar.com/questions/42155/...
Ответ 4
Вы хотите использовать Reflection для достижения этого. Рабочее решение можно найти здесь.
Ответ 5
a Исправить для использования метаданных Класс с метаданныхTypeAttribute от здесь
public T GetAttributeFrom<T>( object instance, string propertyName) where T : Attribute
{
var attrType = typeof(T);
var property = instance.GetType().GetProperty(propertyName);
T t = (T)property.GetCustomAttributes(attrType, false).FirstOrDefault();
if (t == null)
{
MetadataTypeAttribute[] metaAttr = (MetadataTypeAttribute[])instance.GetType().GetCustomAttributes(typeof(MetadataTypeAttribute), true);
if (metaAttr.Length > 0)
{
foreach (MetadataTypeAttribute attr in metaAttr)
{
var subType = attr.MetadataClassType;
var pi = subType.GetField(propertyName);
if (pi != null)
{
t = (T)pi.GetCustomAttributes(attrType, false).FirstOrDefault();
return t;
}
}
}
}
else
{
return t;
}
return null;
}
Ответ 6
Вот как я сделал что-то подобное
/// <summary>
/// Returns the DisplayAttribute of a PropertyInfo (field), if it fails returns null
/// </summary>
/// <param name="propertyInfo"></param>
/// <returns></returns>
private static string TryGetDisplayName(PropertyInfo propertyInfo)
{
string result = null;
try
{
var attrs = propertyInfo.GetCustomAttributes(typeof(DisplayAttribute), true);
if (attrs.Any())
result = ((DisplayAttribute)attrs[0]).Name;
}
catch (Exception)
{
//eat the exception
}
return result;
}