c# - 属性值不反射(reflect)运行时所做的更改

标签 c# custom-attributes

我有一个问题,无法解决: 我制作了一个 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/

相关文章:

c# - Azure 应用服务中具有不同用户权限的单个连接字符串

具有自定义属性的 Android 自定义 View

android - 如何在 java 和 xml 中传递自定义组件参数

c# - 每隔几秒自动刷新或更新内容页面

c# - 前面的类声明 C# 语法,如 [SomeType (someArg1, ..., someArgN)]

c# - 如何使用 asp.net mvc facebook 访问用户的电子邮件 ID?

asp.net-mvc-3 - 无法在 MVC3 HTML Helper 中获取自定义属性值

c# - Windows 10 上的时区偏移量为 "Egypt Standard Time"不正确

.net - 将 native 方法标记为已弃用/过时?

c# - 我可以为属性使用集合初始值设定项吗?