//Get PropertyDescriptor object for the given property name
var propDesc = TypeDescriptor.GetProperties(typeof(T))[propName];
//Get FillAttributes methodinfo delegate
var methodInfo = propDesc.GetType().GetMethods(BindingFlags.Instance | BindingFlags.Public |
BindingFlags.NonPublic)
.FirstOrDefault(m => m.IsFamily || m.IsPublic && m.Name == "FillAttributes");
//Create Validation attribute
var attribute = new RequiredAttribute();
var attributes= new ValidationAttribute[]{attribute};
//Invoke FillAttribute method
methodInfo.Invoke(propDesc, new object[] { attributes });
你好,我正在尝试使用上述代码在运行时添加验证属性。然而,我遇到了以下异常:
集合大小是固定的
SomeClass
的新类,并添加了class level
属性SomeAttribute
,创建了一个实例并验证了结果。就像你可以使用静态方法进行如下操作:[SomeAttribute("Some Value")] public class SomeClassProxy : SomeClass { }; var instance = new SomeClassProxy();
- Jürgen Steinblock