在DynamicProxy Interceptor方法中我有:
public void Intercept(IInvocation invocation)
{
var _attribute = Attribute.GetCustomAttribute(invocation.Method, typeof(OneToManyAttribute), true);
我装饰了我的财产:
[OneToMany(typeof(Address), "IdUser")]
public virtual IList<Address> Addresses { get; set; }
_attribute
始终为null
。
我认为问题是invocation.Method
是自动生成的get_Addresses
而不是装饰的原始属性。
在这种情况下是否有解决方法来检索属性列表?
答案 0 :(得分:1)
你是对的 - 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);