//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属性.但是我得到以下例外:
收集是固定的大小
我正在尝试以编程方式在类成员之上添加新属性......
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Text;
using System.Threading.Tasks;
namespace Test11
{
public class SomeAttribute : Attribute
{
public SomeAttribute(string value)
{
this.Value = value;
}
public string Value { get; set; }
}
// for attribute to be injected the property should be "virtual"
public class ClassA
{
public virtual int Value { get; set; }
}
public class Test
{
public static void Func()
{
var type = typeof(ClassA);
var aName = …Run Code Online (Sandbox Code Playgroud)