简体   繁体   English

在运行时为属性添加属性(出于设计时的目的)

[英]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 MyRuntimeAttribute());

But I can't find any way to do the same for properties. 但是我找不到任何对属性执行相同操作的方法。

Any suggestions? 有什么建议么?

UPD: The exactly task is following: 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") { }
}

I want each of the descendants to have each own DefaultValueAttribute at the Name property with the corresponding default name. 我希望每个后代在Name属性中具有各自的DefaultValueAttribute和相应的默认名称。 And I don't want to hardcode DefaultValueAttribute on each descentand :) 而且我不想在每个descentand上硬编码DefaultValueAttribute :)

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. 请注意,TypeDescriptor实际上也不会向该类添加属性:如果在将属性附加到MyRuntimeAttribute后检查typeof(MyType).GetCustomAttributes(false)返回的数组,您会注意到它不属于该属性。

Since you mention design-time, what you can do is dynamically modify attributes. 既然提到了设计时,那么您可以做的就是动态修改属性。 Is that what you actually want to do? 那是你真正想做的吗?

See also: 也可以看看:

You can also provide a control designer and in that designer you can override PreFilterProperties. 您还可以提供一个控件设计器,在该设计器中,您可以覆盖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 http://www.codeproject.com/KB/webforms/HidingProperties.aspx

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM