//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 });
嗨我想在運行時使用上面的代碼添加驗證屬性。但是我收到以下異常:如何在運行時向屬性添加屬性
收集是一個固定大小的
可能重複的屬性可以動態地在增加C#?](http://stackoverflow.com/questions/129285/can-attributes-be-added-dynamically-in-c) –