开发者

Adding an Attribute for property in runtime (for design-time purposes)

I need to add an attribute to some property in runtime (for design-time purposes). I know I can do this for classes:

TypeDescriptor.AddAttributes(typeof(MyType), new My开发者_如何转开发RuntimeAttribute());

But I can't find any way to do the same for properties.

Any suggestions?

UPD: The exactly task is following:

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") { }
}

I want each of the descendants to have each own DefaultValueAttribute at the Name property with the corresponding default name. And I don't want to hardcode DefaultValueAttribute on each descentand :)


You can't dynamically add or remove attributes. Note that TypeDescriptor doesn't actually add an attribute to the class either: If you check the array that typeof(MyType).GetCustomAttributes(false) returns after you attach your attribute with MyRuntimeAttribute you'll notice that it isn't part of it.

Since you mention design-time, what you can do is dynamically modify attributes. Is that what you actually want to do?

See also:

  • Can attributes be added dynamically in C#?
  • Remove C# attribute of a property dynamically


You can also provide a control designer and in that designer you can override PreFilterProperties. While typically this is used to hide properties, it can also be used to add them.

http://www.codeproject.com/KB/webforms/HidingProperties.aspx

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜