我需要在下面的对象(突出显示)中创建子属性,并且我想像下面一样去做。 除了创建单独的对象并将其附加到主对象之外。
但它没有分配价值,请帮忙。
Test oTest=new oTest(); oTest.Prop1=100; ***oTest.Sub.SubProp3="10";***类定义如下,
public class Test { public int Prop1{ get; set; } public int Prop2{ get; set; } private Subtest _sub = null; public Subtest Sub { get { return (_sub != null) ? _sub : new Subtest(); } set { _sub = value; } } } public class Subtest { public int SubProp1{ get; set; } public int SubProp2{ get; set; } private string _SubProp3; public string SubProp3 { get { return _SubProp3; } set { _SubProp3= value; } } }I have an requirement of creating sub properties in side an object like below(highlighted), And I would like to do it in one go like below. Other than creating separate object and attaching it to main object.
But it is not assigning the value , pls help.
Test oTest=new oTest(); oTest.Prop1=100; ***oTest.Sub.SubProp3="10";***Classes are defined like below,
public class Test { public int Prop1{ get; set; } public int Prop2{ get; set; } private Subtest _sub = null; public Subtest Sub { get { return (_sub != null) ? _sub : new Subtest(); } set { _sub = value; } } } public class Subtest { public int SubProp1{ get; set; } public int SubProp2{ get; set; } private string _SubProp3; public string SubProp3 { get { return _SubProp3; } set { _SubProp3= value; } } }最满意答案
几种选择:
更改字段初始值设定项:
private Subtest _sub = new Subtest();在施工时设置新值:
public Test() { _sub = new Subtest(); }获取时设置新值:
public Subtest Sub { get { if(_sub == null) _sub = new Subtest(); return _sub; } set { _sub = value; } }第三个选项的主要好处是子项的创建被延迟,直到检索到属性。 缺点是具有副作用的吸气剂可能存在问题。
Couple of options:
Change your field initializer:
private Subtest _sub = new Subtest();Set a new value at construction:
public Test() { _sub = new Subtest(); }Set a new value when getting:
public Subtest Sub { get { if(_sub == null) _sub = new Subtest(); return _sub; } set { _sub = value; } }The main benefit of the third option is the creation of the sub-item is delayed until the property is retrieved. The downside is that getters with side-effects can be problematic.
更多推荐
发布评论