相关疑难解决方法(0)

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

//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万
查看次数

使用 Reflection.Emit 以编程方式为现有类属性添加新属性

我正在尝试以编程方式在类成员之上添加新属性......

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)

c# reflection.emit

2
推荐指数
1
解决办法
1047
查看次数

标签 统计

c# ×2

attributes ×1

reflection.emit ×1