.net 只读属性问题
.net
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Test t = new Test
{
TestField = { new Student { Name = "ss", Age = 111 } }//TestField是只读的 怎么 还能这么写
};
}
}
public class Student
{
public string Name { get; set; }
public int Age { get; set; }
}
public class Test
{
public StuCollection _testField;
public StuCollection TestField
{
get
{
if (_testField == null)
{
_testField = new StuCollection();
}
return _testField;
}
}
}
public class StuCollection : List<Student>
{
}
分享到:
[解决办法]
Test t = new Test
{
TestField = {
new Student { Name = "ss", Age = 111 },
new Student{Name="asd",Age=222}
}
};
这是集合初始化器,TestField属性是集合,这种语法是向集合添加子项的,不是给属性赋值。
Test t = new Test
{
TestField =new StuCollection();这才是给属性赋值。
};
http://www.cnblogs.com/linianhui/archive/2011/03/27/1996997.html你可以看看这篇文章。
[解决办法]
Test t = new Test
{
TestField = { new Student { Name = "ss", Age = 111 } }//TestField是只读的 怎么 还能这么写
};
Test t = new Test编译出来的代码(IL代码)都有这篇文章所说的所谓Add代码。而这篇文章只不过说到了Add方法而已,因此它没有解释这两个的区别。
{
TestField = new StuCollection{ new Student { Name = "ss", Age = 111 } }//为 TestField属性增加一个Set方法,以便编译通过
};