public class Test
{
private string _testname;
public string testname
{
set { _testname = value; }
get { return _testname; }
}
public Test():this("test")
{ }
public Test(string test)
{
this.testname = test;
}
private string _testname; 属于字段
public string testname
{
set { _testname = value; }
get { return _testname; }
} 属于属性
这样定义是为了让外部只能通过属性来访问字段
字段是 private的
属性是public 的
当然你这个例子在编码规范上有点问题。
正确的编码规范是
字段首字母小写 应为他是一个变量
属性首字母要大写
如有问题可以继续评论。
望采纳
这是C#早期的写法,前面是私有的字段,后面是属性,写法上的确如你所想的,很罗嗦。
C# 3.0(VS2008+)以后可以写
public class Test
{
public string testname { get; set; } //这一行就相当于你前面那两遍重复的定义
public Test():this("test") //这里定义了2个构造函数,这个是无参数构造函数,调用了下面的有参数构造函数
{ }
public Test(string test)
{
this.testname = test;
}
顺便说下,这种代码的写法是很常见的,微软的类库就是这么写的(我随便找的两个源代码,你也可以去看别的,是不是都这么写)
来自 https://referencesource.microsoft.com/
完整的定义方法是这样的,现在你可以直接定义成public string testname{get;set;} 编译器会在编译时自动补完整,完整的定义方法也是有好处的,比如可以对get,set做更多控制,比如set里面加上private以限制外部访问,还可以在get,set里面加上对其他方法的调用:
private string _testname;
public string testname
{
set { _testname = value; FuncXX(); }
get { return _testname; }
}
WPF在使用MVVM时就是在ViewModel的set内调用页面数据更新通知以刷新页面数据