首页 > 解决方案 > 如何在运行时为类的新实例设置属性值

问题描述

当我创建对象时,我试图在方法上设置一个属性,但不确定如何去做(或者如果可能的话)。

这是我迄今为止尝试过的:

public abstract class AbstractClass
{
    public abstract string DynamicAttributeValue { get; }

    public AbstractClass()
    {
        // Set the Attribute on THIS instance
        TypeDescriptor.AddAttributes(typeof(AbstractClass).GetMethod("MyMethod"),
            new Attribute[] {
                new ConditionalAttribute(DynamicAttributeValue)
        });
    }

    public void MyMethod()
    {
    }
}

class MyConcreteClass : AbstractClass
{
    public override string DynamicAttributeValue => "MyRunTimeValue";

    static void Main(string[] args)
    {
        MyConcreteClass myClass = new MyConcreteClass();

        string callingMethodName = "MyMethod";
        MethodInfo methodInfo = myClass.GetType().GetMethod(callingMethodName);

        var attributes = methodInfo.GetCustomAttributes();
    }
}

标签: c#.netreflectionattributestypedescriptor

解决方案


推荐阅读