获取给定名称的属性的默认值
我有一个财产(示例如下)。
[DefaultValue(false)]
public bool MyProperty {
get {
return myVal;
}
set {
myVal=value;
}
}
我使用它的情况是确保如果未设置默认值,它在 PropertyGrid 中显示为粗体。
我发现非常烦人的是,在我的构造函数中,我必须设置属性的初始值,并希望它们匹配。
是否可以让我的构造函数“发现”给定属性的默认值,并进行相应的设置?像这样的东西:
myctor()
{
myVal = GetDefaultValueProperty<bool>("MyProperty");
}
I have a property, (example shown below).
[DefaultValue(false)]
public bool MyProperty {
get {
return myVal;
}
set {
myVal=value;
}
}
The situation I'm using this is to make sure it shows up as bold in the a PropertyGrid if the default value is not set.
I find it incredibly annoying that in my constructor, I have to set the initial value of my property, and hope that they match up.
Is it possible to have my constructor "discover" the default value of a given property, and set it accordingly? Something like:
myctor()
{
myVal = GetDefaultValueProperty<bool>("MyProperty");
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用以下代码来获取您想要的元数据。
如果您想做一些真正的事情,您可以使用 Lambda 表达式来实现:
用法如下:
You can use the following code to get the metadata you're after.
If you want to do something really cool, you can do this with a Lambda expression:
Usage is then:
您可以调用
GetProperty
方法来查找属性,然后调用GetCustomAttributes(typeof(DefaultValueAttribute)
(并转换其结果)来获取应用的属性。You can call the
GetProperty
method to find the property, then callGetCustomAttributes(typeof(DefaultValueAttribute)
(and cast its result) to get the attribute applied.这是基于 Paul Turner 的答案的通用扩展方法。它适用于任何类别的任何成员。
或者,如果未找到该属性,您可以接受返回默认值,请使用此:
您还可以修改它以在未找到该属性时引发异常。
Here's a generic extension method based on Paul Turner's answer. It will work for any member of any class.
Alternatively, you're OK with the default value being returned if the attribute was not found, use this:
You could also modify it to throw an exception if the attribute wasn't found.