EnterpriseLibrary Validation的配置导致AmbiguousMatchException问题

来源:互联网 发布:淘宝详情页制作步骤 编辑:程序博客网 时间:2024/05/13 00:59
前几天在用EL的Validation进行App.Config配置时遇到了比较头疼的情况: 在对隐藏父类成员(一般为属性)的子类成员进行配置时一切正常,但是在运行后就抛出了

System.Reflection.AmbiguousMatchException异常,查了EL的源码,发现源头出在了ValidationReflectionHelper类中的GetProperty方法中,如下:

internal static PropertyInfo GetProperty(Type type, string propertyName, bool throwIfInvalid)        {            if (string.IsNullOrEmpty(propertyName))            {                throw new ArgumentNullException("propertyName");            }            PropertyInfo propertyInfo = type.GetProperty(propertyName,BindingFlags.Public | BindingFlags.Instance);                     ...//省略            }

问题就出在红色标记处,因为在反射调用时父类和子类各有一个同名的属性,在运行时就会抛出匹配的异常,解决这个问题就只能改源码了:

... internal static PropertyInfo GetProperty(Type type, string propertyName, bool throwIfInvalid)        {            if (string.IsNullOrEmpty(propertyName))            {                throw new ArgumentNullException("propertyName");            }            PropertyInfo propertyInfo = null;            try            {                propertyInfo = type.GetProperty(propertyName, BindingFlags.Public | BindingFlags.Instance);            }            catch (AmbiguousMatchException )            {                propertyInfo = type.GetProperty(propertyName, BindingFlags.DeclaredOnly |  BindingFlags.Public | BindingFlags.Instance);            }                    ...            return propertyInfo;        }...

在获取属性时仅考虑子类的成员即可。改完源码后需要对原程序集进行重新编译,可能还得添加强命名,并且对App配置文件中关于Validation段的设置都要进行修改,重新运行后问题解决。

原创粉丝点击