首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > .NET > C# >

.net 只读属性有关问题

2013-09-24 
.net 只读属性问题public partial class WebForm1 : System.Web.UI.Page{protected void Page_Load(object

.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> 
    {
    }
.net

分享到:
[解决办法]
  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 },
                        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
            {
                TestField = new StuCollection{ new Student { Name = "ss", Age = 111 } }//为 TestField属性增加一个Set方法,以便编译通过
            };
编译出来的代码(IL代码)都有这篇文章所说的所谓Add代码。而这篇文章只不过说到了Add方法而已,因此它没有解释这两个的区别。

热点排行