加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 在运行时更改自定义属性的参数

发布时间:2020-12-15 06:54:24 所属栏目:百科 来源:网络整理
导读:在运行时我需要change属性的参数.我把我的问题简化为简单的例子. 属性类: [AttributeUsage(AttributeTargets.Property)] public class MyAttribute : Attribute { public string Name { get; set; } } 具有属性的简单实体: public class MyEntity { [MyAtt
在运行时我需要change属性的参数.我把我的问题简化为简单的例子.

属性类:

[AttributeUsage(AttributeTargets.Property)]
    public class MyAttribute : Attribute
    {
        public string Name { get; set; }
    }

具有属性的简单实体:

public class MyEntity
    {
        [MyAttribute(Name="OldValue1")]
        public string Data1{ get; set; }

        [MyAttribute(Name = "OldValue2")]
        public string Data2 { get; set; }
    }

我创建了MyEntity类的instace.我可以改变对象属性的值,但是我不能更改对象实体上属性的属性名称的值.可能吗?

对象实体的属性值我可以用这部分代码来改变:

entityProp.SetValue(entity,"NewData",null);

但是我不知道如何在对象实体上改变属性的属性名称的值

这不行:

06003

名称的价值仍然是原始的.

这是所有测试代码.谢谢你的地狱

[TestMethod]
    public  void Test()
    {
        var entity = new MyEntity
                         {
                             Data1 = "OldData",Data2 = "OldData"
                         };

        PropertyInfo[] entityProps = entity.GetType().GetProperties();

        foreach (var entityProp in entityProps)
        {
            var attribute = Attribute.GetCustomAttribute(entityProp,typeof (MyAttribute)) as MyAttribute;

            if (attribute != null)
            {
                //get attribute’s property NAME
                PropertyInfo attProp= attribute.GetType().GetProperty("Name");

                //get entity property value
                var propertyValue = entityProp.GetValue(entity,null);

                //get attribute’s property NAME value
                var atributeNameValue = attProp.GetValue(entity,null);

                TestContext.WriteLine(string.Format("property name:{0} property value: {1} : atribute name value: {2}n",entityProp.Name,propertyValue,atributeNameValue)); 

                //change values
                entityProp.SetValue(entity,null);

                //how can I change value of property Name on object entity ?
                attProp.SetValue(attribute,null);

            }

        }

        TestContext.WriteLine(string.Format("After changen"));

        foreach (var entityProp in entityProps)
        {
            var attribute = Attribute.GetCustomAttribute(entityProp,typeof(MyAttribute)) as MyAttribute;

            if (attribute != null)
            {

                PropertyInfo attProp = attribute.GetType().GetProperty("Name");

                var propertyValue = entityProp.GetValue(entity,null);
                var atributeNameValue = attProp.GetValue(entity,atributeNameValue));
            }
        }



    }

EDITED:我删除原帖并添加非常简单的清晰样本.抱歉

解决方法

您不能在运行时更改属性.它们嵌入到程序集的元数据中.您的方法正在改变特定实例的内部状态;但是当您再次加载属性时,您将获得不同的实例.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读