我有一个问题,无法解决: 我制作了一个 mathode,它应该设置特定属性“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;
}
最佳答案
属性不会存储在程序集元数据之外的任何地方。它们仅在反射要求时具体化为属性实例 - 在您的情况下通过GetCustomAttributes<MappingAttribute>
.但是:你然后丢弃这些。下次GetCustomAttributes<MappingAttribute>
被调用时,新的新实例将被分发,其中包含程序集元数据中的值。
基本上:更新属性实例的属性不意味着当该代码询问属性元数据时其他代码将看到这些更改。
为了说明这一点:
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"
}
}
关于c# - 属性值不反射(reflect)运行时所做的更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49752565/