你是对的 -invocation.Method
将是属性访问器,而不是属性。
这是一个实用方法,用于查找PropertyInfo
与其访问器方法之一相对应的方法:
public static PropertyInfo PropertyInfoFromAccessor(MethodInfo accessor)
{
PropertyInfo result = null;
if (accessor != null && accessor.IsSpecialName)
{
string propertyName = accessor.Name;
if (propertyName != null && propertyName.Length >= 5)
{
Type[] parameterTypes;
Type returnType = accessor.ReturnType;
ParameterInfo[] parameters = accessor.GetParameters();
int parameterCount = (parameters == null ? 0 : parameters.Length);
if (returnType == typeof(void))
{
if (parameterCount == 0)
{
returnType = null;
}
else
{
parameterCount--;
returnType = parameters[parameterCount].ParameterType;
}
}
if (returnType != null)
{
parameterTypes = new Type[parameterCount];
for (int index = 0; index < parameterTypes.Length; index++)
{
parameterTypes[index] = parameters[index].ParameterType;
}
try
{
result = accessor.DeclaringType.GetProperty(
propertyName.Substring(4),
returnType,
parameterTypes);
}
catch (AmbiguousMatchException)
{
}
}
}
}
return result;
}
使用此方法,您的代码将变为:
var _attribute = Attribute.GetCustomAttribute(invocation.Method, typeof(OneToManyAttribute), true);
if (_attribute == null && invocation.Method.IsSpecialName)
{
var property = PropertyInfoFromAccessor(invocation.Method);
if (property != null)
{
_attribute = Attribute.GetCustomAttribute(property, typeof(OneToManyAttribute), true);
}
}
如果你OneToManyAttribute
只适用于属性,而不是方法,你可以省略第一次调用GetCustomAttribute
:
var property = PropertyInfoFromAccessor(invocation.Method);
var _attribute = (property == null) ? null : Attribute.GetCustomAttribute(property, typeof(OneToManyAttribute), true);