C# 从属性生成的方法检索CustomAttribute
在DynamicProxy拦截器方法中,我有:C# 从属性生成的方法检索CustomAttribute,c#,castle-dynamicproxy,C#,Castle Dynamicproxy,在DynamicProxy拦截器方法中,我有: public void Intercept(IInvocation invocation) { var _attribute = Attribute.GetCustomAttribute(invocation.Method, typeof(OneToManyAttribute), true); 我把我的房子装饰成这样: [OneToMany(typeof(Address), "IdUser")] public virtua
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; }
[OneToMany(地址类型),“IdUser”)]
公共虚拟IList地址{get;set;}
\u属性
始终为null
我认为问题在于,invocation.Method
是自动生成的get\u Addresses
而不是修饰的原始属性
在这种情况下,是否有办法检索属性列表?您是正确的-调用的
方法将是属性访问器,而不是属性
下面是一个实用方法,用于查找与其访问器方法之一对应的属性info
:
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;
}
如果您的OneToManyAttribute
仅适用于属性,而不适用于方法,则可以省略对GetCustomAttribute
的第一次调用:
var property = PropertyInfoFromAccessor(invocation.Method);
var _attribute = (property == null) ? null : Attribute.GetCustomAttribute(property, typeof(OneToManyAttribute), true);
var property = PropertyInfoFromAccessor(invocation.Method);
var _attribute = (property == null) ? null : Attribute.GetCustomAttribute(property, typeof(OneToManyAttribute), true);