为了处理类中成员属性的默认值,误以为使用DefaultValueAttribute可以简化解决, 最终发现是错误的
命名空间:using System.ComponentModel;
using System.ComponentModel;
public class DemoModel
{
[DefaultValue("0000")]
public string st_no { get; set; };
}
经测试发现st_no 的默认值仍为NULL值。
查阅之后 ,才发现理解是错的,MSDN的解释:
A DefaultValueAttribute will not cause a member to be automatically initialized with the attribute's value. You must set the initial value in your code.
DefaultValueAttribute并不能自动初始化一个字段,必须在代码中手动初始化字段。
另外这个特性主要是供可视化设计器使用
怎么办????
尝试一下,默认赋值的方式,经测试,成功。其他类型的属性成员 也可以这样子赋值。
public class DemoModel
{
public string st_no { get; set; }="0000";
}