【发布时间】: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