首页 新闻 会员 周边

VS2008的自动属性支持默认值吗?

0
[已关闭问题]

[DefaultValue(true)]
public bool EnableShow { get; set; }

因为bool默认为false,但我希望默认为true。用了上面的方式,但好像没效果。所以请问vs2008的自动属性支持默认值吗?
∈鱼杆的主页 ∈鱼杆 | 菜鸟二级 | 园豆:205
提问于:2008-09-17 18:10
< >
分享
其他回答(4)
0

老大,字体太小了吧,我看了头晕

Code
  [Description("状态"), DefaultValue(true)]
public bool EnableShow
{
get
{
object o = ViewState["EnableShow"];
if ((o != null) && (o.ToString().ToLower() == "false"))
{
return false;
}
else
{
return true;
}
}
set
{
ViewState[
"EnableShow"] = value;
}

}
zjy | 园豆:3194 (老鸟四级) | 2008-09-17 18:25
0

楼上的,为啥不直接硬转换?

Code
[Description("状态"), DefaultValue(true)]
public bool EnableShow {
get {
object o = ViewState["EnableShow"];
return o == null ? true : (bool)o;//注意这里的 true 表示默认情形
}
set {
ViewState[
"EnableShow"] = value;
}
}

陛下 | 园豆:3938 (老鸟四级) | 2008-09-17 18:32
0

的确存在楼主所说的现象,可以通过以下代码示例说明问题。

 

代码示例
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 可视化设计器利用这个来重置成员值。

如果想要达到楼主的目的,自动属性这个语法糖无法实现。

Angel Lucifer | 园豆:775 (小虾三级) | 2008-09-17 19:09
0

自动属性不支持default value和readonly,对于default value可以在构造函数中给他赋个值

Gray Zhang | 园豆:17610 (专家六级) | 2008-09-17 21:40
0

对嘛,构造函数直接赋值就OK了

天堂口 | 园豆:514 (小虾三级) | 2008-09-18 10:59
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册