【问题标题】:Attribute values do not reflect changes made at runtime属性值不反映运行时所做的更改
【发布时间】:2018-04-10 11:32:58
【问题描述】:

我有一个问题,无法解决: 我做了一个数学模型,它应该设置特定属性“MappingAttribute”的属性值并返回新对象。

问题: 属性值始终设置为默认值“false”。 我哪里错了?

    static public T MapToClass<T>(SqlDataReader reader) where T : class
    {
        T returnedObject = Activator.CreateInstance<T>();
        PropertyInfo[] modelProperties = returnedObject.GetType().GetProperties();
        for (int i = 0; i < modelProperties.Length; i++)
        {
            MappingAttribute[] attributes = modelProperties[i].GetCustomAttributes<MappingAttribute>(true).ToArray();


            if (attributes.Length > 0) {
                attributes[0].AutoIncrement = true;
                attributes[0].Primekey = true;
            }
        }
        return returnedObject;
    }

【问题讨论】:

  • 注意:这些都不是“自定义属性”——它们是“属性”;更改标签/标题

标签: c# custom-attributes


【解决方案1】:

属性不存储除了在程序集元数据中的任何地方。仅当通过反射要求它们实现属性 instances 时,它们才会具体化 - 在您的情况下是通过 GetCustomAttributes&lt;MappingAttribute&gt; 实现的。但是:然后你丢弃这些。下次调用 GetCustomAttributes&lt;MappingAttribute&gt; 时,将分发新实例,其中包含程序集元数据中的值。

基本上:更新属性实例的属性意味着当该代码询问属性元数据时其他代码会看到这些更改。

为了说明这一点:

using System;
class FooAttribute : Attribute { public string Value { get; set; } }

[Foo(Value = "abc")]
class Bar
{
    static void Main()
    {
        var attrib = (FooAttribute)typeof(Bar)
            .GetCustomAttributes(typeof(FooAttribute), false)[0];
        Console.WriteLine(attrib.Value); // "abc"
        attrib.Value = "def";
        Console.WriteLine(attrib.Value); // "def"

        // now re-fetch
        attrib = (FooAttribute)typeof(Bar)
            .GetCustomAttributes(typeof(FooAttribute), false)[0];
        Console.WriteLine(attrib.Value); // "abc"
    }
}

【讨论】:

  • 感谢您的详细解释。现在我明白了!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-02
  • 2022-01-11
  • 2021-01-12
  • 1970-01-01
相关资源
最近更新 更多