RK.*_*RK. 2 c# linq extension-methods custom-attributes
我想通过使用扩展方法检查我的类成员(仅限字段)上的自定义属性.
public class DatabaseIdAttribute : Attribute
{
public int ID { get; set; }
public DatabaseIdAttribute(int id)
{
this.ID = id;
}
}
public class MyClass
{
[DatabaseId(1)]
double Height {get;set;}
[DatabaseId(2)]
double Width {get;set;}
double Area { get { return this.Height * this.Width; }
}
Run Code Online (Sandbox Code Playgroud)
我想在扩展方法中使用LINQ表达式来访问类字段而不是传递魔术字符串.
var myClass = new MyClass();
var attribute = myClass.GetAttribute<DatabaseIdAttribute>(c => c.Height);
Run Code Online (Sandbox Code Playgroud)
有可能实现吗?
[编辑]
目前,我已经在@leppie的帮助下取得了以下成绩
public static MemberInfo GetMember<T, R>(this T instance, Expression<Func<T, R>> selector)
{
var member = selector.Body as MemberExpression;
if (member != null)
{
return member.Member;
}
return null;
}
public static T GetAttribute<T>(this MemberInfo member) where T : Attribute
{
return member.GetCustomAttributes(false).OfType<T>().SingleOrDefault();
}
Run Code Online (Sandbox Code Playgroud)
这使得能够以下列方式获取属性
var c = new MyClass();
var attribute = c.GetMember(m => m.Height).GetAttribute<DatabaseIdAttribute>();
Run Code Online (Sandbox Code Playgroud)
但我希望能够以下列方式访问它
var c = new MyClass();
var attribute = c.GetAttribute<DatabaseIdAttribute>(m => m.Height);
Run Code Online (Sandbox Code Playgroud)
你快到了!这应该工作(未经测试).
public static class ObjectExtensions
{
public static MemberInfo GetMember<T,R>(this T instance,
Expression<Func<T, R>> selector)
{
var member = selector.Body as MemberExpression;
if (member != null)
{
return member.Member;
}
return null;
}
public static T GetAttribute<T>(this MemberInfo meminfo) where T : Attribute
{
return meminfo.GetCustomAttributes(typeof(T)).FirstOrDefault() as T;
}
}
Run Code Online (Sandbox Code Playgroud)
用法:
var attr = someobject.GetMember(x => x.Height).
GetAttribute<DatabaseIdAttribute>();
Run Code Online (Sandbox Code Playgroud)
IIRC:GetAttribute<T>(this MemberInfo meminfo)已经被定义为.NET 4中的扩展方法.