我正在为属性构建自己的库,我想检查属性级别是否有属性。目前我有这种方法可以正常工作:
public static bool HasPropertyAttribute<T>(this object instance, string propertyName)
{
return Attribute.GetCustomAttributes(instance.GetType().GetProperty(propertyName), typeof(T), true).Any();
}
现在我正在寻找能让我传递lambda表达式而不是string作为propertyName的解决方案。是否有一种优雅的方式来做到这一点,而不添加此方法成为两个通用类型依赖,aka:
HasPropertyAttribute<T, TProperty>(...).
答案 0 :(得分:6)
您可以使用Lambda表达式来解析编译时属性引用。 (代码从Retrieving Property name from lambda expression修改)
public PropertyInfo GetPropertyInfo<TProperty>(
Expression<Func<TProperty>> propertyLambda)
{
MemberExpression member = propertyLambda.Body as MemberExpression;
if (member == null)
throw new ArgumentException(string.Format(
"Expression '{0}' refers to a method, not a property.",
propertyLambda.ToString()));
PropertyInfo propInfo = member.Member as PropertyInfo;
if (propInfo == null)
throw new ArgumentException(string.Format(
"Expression '{0}' refers to a field, not a property.",
propertyLambda.ToString()));
return propInfo;
}
您不需要将它用作扩展方法(但如果您想要调整它,可以,但除了编写行之外没有必要使用源对象实例)
public class Test
{
public string Prop { get; set; }
}
Test t = new Test();
PropertyInfo propInfo = GetPropertyInfo(() => t.Prop);
Console.WriteLine(propInfo.Name + " -> " + propInfo.PropertyType); //Prop -> System.String
编辑:如果你想要一些很好的语法并且必须避免对该类型的对象进行现有引用,你可以这样做:
public static class TypedReflection<TSource>
{
public static PropertyInfo GetPropertyInfo<TProperty>(
Expression<Func<TSource, TProperty>> propertyLambda)
{
MemberExpression member = propertyLambda.Body as MemberExpression;
if (member == null)
throw new ArgumentException(string.Format(
"Expression '{0}' refers to a method, not a property.",
propertyLambda.ToString()));
PropertyInfo propInfo = member.Member as PropertyInfo;
if (propInfo == null)
throw new ArgumentException(string.Format(
"Expression '{0}' refers to a field, not a property.",
propertyLambda.ToString()));
return propInfo;
}
}
并称之为:
PropertyInfo propInfo = TypedReflection<Test>.GetPropertyInfo(o => o.Prop);
此时,添加其他类型反射方法(获取方法,字段等)非常容易。
编辑:它仍然是两种依赖的通用类型,但它通过类型推断隐藏起来。我更喜欢第二个例子;至少你需要指定声明类类型(因为你想要类型安全),但是你不需要一个对象实例。它也有好处(我怀疑你在追求),如果你重命名属性,它会传播到这个代码获得PropertyInfo
。
答案 1 :(得分:0)
我选择了这个解决方案,至少是所有代码:
public static bool HasPropertyAttribute<T, TProperty>(this T instance, Expression<Func<T, TProperty>> propertySelector, Type attribute)
{
return Attribute.GetCustomAttributes(instance.GetType().GetProperty((propertySelector.Body as MemberExpression).Member.Name), attribute, true).Any();
}
像这样调用:
var cc = new CustomClass();
cc.HasPropertyAttribute(x => x.Name, typeof(NullableAttribute))