在另一个对象中分配和调用Object属性(Assigning and calling Object properties inside another object)

系统教程 行业动态 更新时间:2024-06-14 17:03:54
在另一个对象中分配和调用Object属性(Assigning and calling Object properties inside another object)

我需要在下面的对象(突出显示)中创建子属性,并且我想像下面一样去做。 除了创建单独的对象并将其附加到主对象之外。

但它没有分配价值,请帮忙。

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.

更多推荐

本文发布于:2023-04-24 14:24:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/dzcp/570237e001b9ea02f78b8cd4fef3db69.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:属性   分配   对象   properties   object

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!