2010-07-12 130 views
0

我需要在运行时为某个属性添加属性(用于设计时)。我知道我可以这样做类:在运行时为属性添加属性(用于设计时间目的)

TypeDescriptor.AddAttributes(typeof(MyType), new MyRuntimeAttribute());

但我找不到任何方法来做同样的属性。

有什么建议吗?

UPD:完全相同任务如下:

public class BaseClass { 
    public BaseClass(string name) { Name = name; } 
    public Name { get; set; } 
} 
public class Descendant1: BaseClass { 
    public Descendant1() : base("Default Name 1") { } 
} 
... 
public class DescendantN: BaseClass { 
    public DescendantN() : base("Default Name N") { } 
}

我希望每个子孙让每个自己的DefaultValueAttribute在与相应的默认名称的名称属性。而且我不想在每个下降点上对DefaultValueAttribute进行硬编码:)

+0

beresta berestnul! – amartynov 2010-07-14 11:49:34

回答

1

您无法动态添加或删除属性。请注意,TypeDescriptor实际上并没有为该类添加属性:如果在使用MyRuntimeAttribute附加属性后检查typeof(MyType).GetCustomAttributes(false)返回的数组,您将注意到它不属于它。

既然你提到设计时,你可以做的是动态修改属性。那是你真正想要做什么?

参见:

+0

对不起,但没有。 我刚才调查了一下,现在我认为用GetProperties覆盖的TypeConverter实现是我需要的(PropertyDescriptorAdaptor将返回基于http://msdn.microsoft.com/en-us/library/system的修改后的AttributesCollection。 componentmodel.propertydescriptor.aspx文章)。我会在一些测试后在这里发布结果。 不过,谢谢你的第二个链接,回帖里有个很有意思的帖子。 – Beresta 2010-07-12 18:51:33