[DefaultValue(true)]public bool EnableShow { get; set; }因为bool默认为false,但我希望默认为true。用了上面的方式,但好像没效果。所以请问vs2008的自动属性支持默认值吗?
2 回答
DIEA
TA贡献1820条经验 获得超3个赞
的确存在楼主所说的现象,可以通过以下代码示例说明问题。
[object Object]代码示例
using System;
using System.ComponentModel;
namespace Lucifer.CSharp.Sample
{
class Program
{
static void Main()
{
TestClass test = new TestClass();
AttributeCollection attributes =
TypeDescriptor.
GetProperties(test)["EnableShow"].
Attributes;
DefaultValueAttribute attribute =
(DefaultValueAttribute)attributes
[typeof(DefaultValueAttribute)];
Console.WriteLine(
"The default value is: " +
attribute.Value.ToString());
Console.WriteLine(
"The default value is: " +
test.EnableShow.ToString());
}
}
class TestClass
{
[DefaultValue(true)]
public bool EnableShow { get; set; }
}
}
俺以为 DefaultValueAttribute 是用来给代码生成器使用的。比如 Microsoft 的 VS 可视化设计器利用这个来重置成员值。
如果想要达到楼主的目的,自动属性这个语法糖无法实现。
- 2 回答
- 0 关注
- 777 浏览
添加回答
举报
0/150
提交
取消
