小编Thi*_*ran的帖子

如何在运行时向属性添加属性

//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 });
Run Code Online (Sandbox Code Playgroud)

您好我正在尝试使用上面的代码在运行时添加Validation属性.但是我得到以下例外:

收集是固定的大小

c# attributes

51
推荐指数
4
解决办法
6万
查看次数

标签 统计

attributes ×1

c# ×1