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

Thi*_*ran 51 c# attributes

//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属性.但是我得到以下例外:

收集是固定的大小

Jür*_*ock 146

不要让别人告诉你,你做不到.如果你愿意,你可以竞选总统:-)

为了您的方便,这是一个完全有效的例子

public class SomeAttribute : Attribute
{
    public SomeAttribute(string value)
    {
        this.Value = value;
    }

    public string Value { get; set; }
}

public class SomeClass
{
    public string Value = "Test";
}

[TestMethod]
public void CanAddAttribute()
{
    var type = typeof(SomeClass);

    var aName = new System.Reflection.AssemblyName("SomeNamespace");
    var ab = AppDomain.CurrentDomain.DefineDynamicAssembly(aName, AssemblyBuilderAccess.Run);
    var mb = ab.DefineDynamicModule(aName.Name);
    var tb = mb.DefineType(type.Name + "Proxy", System.Reflection.TypeAttributes.Public, type);

    var attrCtorParams = new Type[] { typeof(string) };
    var attrCtorInfo = typeof(SomeAttribute).GetConstructor(attrCtorParams);
    var attrBuilder = new CustomAttributeBuilder(attrCtorInfo, new object[] { "Some Value" });
    tb.SetCustomAttribute(attrBuilder);

    var newType = tb.CreateType();
    var instance = (SomeClass)Activator.CreateInstance(newType);

    Assert.AreEqual("Test", instance.Value);
    var attr = (SomeAttribute)instance.GetType()
        .GetCustomAttributes(typeof(SomeAttribute), false)
        .SingleOrDefault();
    Assert.IsNotNull(attr);
    Assert.AreEqual(attr.Value, "Some Value");

}
Run Code Online (Sandbox Code Playgroud)

  • 竖起大拇指为励志说话! (67认同)
  • 这为类添加了属性,而不是类的属性,对吗? (6认同)
  • @Denny是的,但是概念是相同的。属性必须是虚拟的才能正常工作,并且您需要发出一些IL代码。这个[问题](http://stackoverflow.com/q/8720275/98491)应该可以帮助您。 (3认同)
  • @JeromeJ代码动态创建一个新类,该新类继承自“ SomeClass”,并添加“类级别”属性“ SomeAttribute”,创建一个实例并验证结果。就像您可以静态使用`[SomeAttribute(“ Some Value”))]公共类SomeClassProxy:SomeClass {}; var instance = new SomeClassProxy();` (2认同)

Ndu*_* Jr 10

楼上的回答太棒了。最近,开发了一个库,它消除了所有的复杂性,并为您提供了像这样简单的东西:

var attributeType = typeof(CustomAAttribute);
var attributeParams = new object[] { "Jon Snow" };
var typeExtender = new TypeExtender("ClassA");
typeExtender.AddProperty("IsAdded", typeof(bool), attributeType, attributeParams);
Run Code Online (Sandbox Code Playgroud)

跟...共事。有关如何安装和使用该库的详细信息,请参阅此处

免责声明:我开发了这个库,并且我已经将它用于很多项目,它就像魔术一样工作

  • 但您无法将属性添加到*现有*属性,可以吗? (6认同)

Ale*_*oma 5

使用我开发的FastDeepCloner 。

public class test{
    public string Name{ get; set; }
}

var prop = DeepCloner.GetFastDeepClonerProperties(typeof(test)).First();
prop.Attributes.Add(new JsonIgnoreAttribute());
// now test and se if exist 
prop = DeepCloner.GetFastDeepClonerProperties(typeof(test)).First();
bool containAttr = prop.ContainAttribute<JsonIgnoreAttribute>()
// or 
JsonIgnoreAttribute myAttr = prop.GetCustomAttribute<JsonIgnoreAttribute>();
Run Code Online (Sandbox Code Playgroud)


Art*_*ess -13

无法在运行时添加属性。属性是静态的,不能添加或删除。

类似问题: