【问题标题】:Modifying Class Attribute on Runtime在运行时修改类属性
【发布时间】:2011-06-16 12:48:52
【问题描述】:

我不确定我是否见过:
Change Attribute's parameter at runtime.
我的情况非常相似,但我试图在运行时更改一个类的属性:

[Category("Change me")]
public class Classic
{
    public string Name { get; set; }
}

其中一个答案是:

Dim prop As PropertyDescriptor = TypeDescriptor
    .GetProperties(GetType(UserInfo))("Age")
Dim att As CategoryAttribute = DirectCast(
     prop.Attributes(GetType(CategoryAttribute)),
     CategoryAttribute)
Dim cat As FieldInfo = att.GetType.GetField(
     "categoryValue",
      BindingFlags.NonPublic Or BindingFlags.Instance)
cat.SetValue(att, "A better description")

感谢 Marc Gravell,已更改为更易读的格式:

TypeDescriptor.AddAttributes(table, new Category{ Name = "Changed" });

使用 TypeDescriptor 时一切正常,但使用时:

var attrs = (Category[])typeof(Classic).GetCustomAttributes(
    typeof(Category),
    true);
attrs[0].Name

名称有“改变我”的文字。
有没有办法在运行时改变这个属性?

编辑:
我需要这个用于设计器中的 Linq2Sql 生成的代码具有 DB 模式。我想使用用户的默认架构而不使用 XML 映射或更改生成的代码(表仍处于开发阶段,经常更改)。

设计器代码为:

[global::System.Data.Linq.Mapping.TableAttribute(Name="DbSchema.MyTable")]
public partial class MyTable

我希望属性是:

[TableAttribute(Name="MyTable")] 

现在我已经深入研究了框架代码,我认为 linq2sql 使用:

TableAttribute[] attrs = (TableAttribute[])typeof(MyTable)
   .GetCustomAttributes(typeof(TableAttribute), true);

当我使用 TypeDescriptor 更改属性时,GetCustomAttributes 中的值没有更改。

【问题讨论】:

  • 为什么要这样做?属性旨在提供元数据,仅此而已。为什么不采用最初由属性填充并从那里更改的“规则列表”的方法?
  • 你想达到什么目的?本地化类别中的文本?
  • @vcsjones 信不信由你,有时您需要在运行时添加、更改或删除属性。我必须这样做才能将转换器添加到 WPF 绑定,以便它们被序列化而不是被评估。
  • 我很困惑 - 为什么您希望更改 Classic 的 Name 会影响类别?
  • 另外 - TypeDescriptor 代码本身非常脆弱;一个不错的答案是使用 TypeDescriptor.AddAttributes 和 TypeDescriptor.GetAttributes - 不要在属性实例上使用反射。

标签: c# linq-to-sql reflection .net-3.5 attributes


【解决方案1】:

完全避免反射,您可以通过TypeDescriptor:

using System;
using System.ComponentModel;
using System.Linq;
[Category("nice")]
class Foo {  }
static class Program
{
    static void Main()
    {
        var ca = TypeDescriptor.GetAttributes(typeof(Foo))
              .OfType<CategoryAttribute>().FirstOrDefault();
        Console.WriteLine(ca.Category); // <=== nice
        TypeDescriptor.AddAttributes(typeof(Foo),new CategoryAttribute("naughty"));
        ca = TypeDescriptor.GetAttributes(typeof(Foo))
              .OfType<CategoryAttribute>().FirstOrDefault();
        Console.WriteLine(ca.Category); // <=== naughty
    }
}

【讨论】:

  • 好吧,当我使用 TypeDescriptor 时,它并没有真正起作用,我得到了改变的值。但是 linq2sql (我需要这个)使用 (TableAttribute[])table.GetCustomAttributes(typeof(TableAttribute), true) 获得原始值...
【解决方案2】:

如果你使用 reflection,那么就不是这样了 - reflection 属性不能被替换 - 只有 component-model 视图是受TypeDescriptor 影响。但是,您可以将CategoryAttribute 子类化为您的目的。对 i18n 尤其有用。

using System.ComponentModel;
using System;
[MyCategory("Fred")]
class Foo {  }
static class Program
{
    static void Main()
    {
        var ca = (CategoryAttribute)Attribute.GetCustomAttribute(typeof(Foo), typeof(CategoryAttribute));
        Console.WriteLine(ca.Category);
              // ^^^ writes "I was Fred, but not I'm EVIL Fred"
    }
}
class MyCategoryAttribute : CategoryAttribute
{
    public MyCategoryAttribute(string category) : base(category) { }
    protected override string GetLocalizedString(string value)
    {
        return "I was " + value + ", but not I'm EVIL " + value;
    }
}

【讨论】:

  • 不幸的是,我无法更改原始属性,也无法创建自己的版本。 Linq2Sql 需要 TableAttribute。
【解决方案3】:

您需要对属性进行编码,使其支持运行时值。例如,验证属性通过设置资源类型和资源字符串来支持消息的国际化,而不是静态消息字符串。

另一种方法是使用 IOC 容器(例如 StructureMap 或 Unity)来提供一些提供值的对象/服务。

如果您不想将属性耦合到特定容器,请使用模式和实践组提供的 Common ServiceLocator 包装器。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多