如何在调用 c# 对象属性值的“get”时设置 c# 对象属性值
本文关键字:对象 属性 get 设置 调用 | 更新日期: 2023-09-27 18:33:25
我只是想看看是否有办法做到这一点。 我有两个班级。一个作为另一个属性存在。 所以在某种程度上它就像父子类关系。 但是我想在此刻设置子对象的值,它的"get"是根据父对象中存在的值调用的。仅当它存在且不为 null 时。
如果子对象已经设置好,我也不想设置子对象......我只是要让机制尽可能简单,这无非是弄清楚热去做。
我的孩子班是
class ChildObject
{
public int? some_val { get; set; }
}
我的父类是
class ParentObject
{
public int? some_val { get; set; }
public ChildObject child
{
get {
//if the chld hasnt been set already
if (child == null)
{
//if the value of the integer has been set
if(some_val != null)
{
//some some method that sets the objects value
//based on teh value of the integer property
SomeMethod();
}
}
return child;
}
set { child = value;}
}
private void SomeMethod()
{
int new_val = this.some_val.Value + 5;
this.child = new ChildObject { some_val = new_val };
}
}
}
在其他一些例程中..就像控制台应用程序的程序或我执行以下操作的任何内容
ParentObject p = new ParentObject ();
p.some_val = 1;
ChildObject c = p.child;
int i = c.some_val.Value;
理想情况下,我想添加一些检查以查看父对象中的"some_val"是否已更改,如果是,请重新"设置"子对象...但现在我只是想弄清楚如何在第一次调用它的 get 时设置属性。
由于某种原因,当我运行时它只是崩溃,而且没有任何例外。 我尝试将例程包装在 try catch 中以查看问题所在,但它只是停止运行并关闭执行控制台程序。
这里的问题是,当您要向get
或set
方法添加一些逻辑时,您需要包含一个包含实际值的字段。问题出现是因为您实际上在那里有一个无限循环并且可能出现 SO 异常。发生这种情况是因为当你得到你的child
时,你称它为getter,它再次在这里:return _child;
。
public int? some_val { get; set; }
private ChildObject _child;
public ChildObject child
{
get {
//if the chld hasnt been set already
if (_child == null)
{
//if the value of the integer has been set
if(some_val != null)
{
//some some method that sets the objects value
//based on teh value of the integer property
SomeMethod();
}
}
return _child;
}
set { _child = value;}
}
private void SomeMethod()
{
int new_val = this.some_val.Value + 5;
this.child = new ChildObject { some_val = new_val };
}
您应该小心相同的字段或值名称。您应该尝试其他值和字段名称。喜欢这个;
private ChildObject child;
public ChildObject Child
{
get {
//if the chld hasnt been set already
if (child == null)
{
//if the value of the integer has been set
if(some_val != null)
{
SomeMethod();
}
}
return child;
}
set { child = value;}
}
并且您应该资源封装原则。祝你好运。
您可以使用另一个字段来执行此操作
public int? some_val { get; set; }
public ChildObject _child;
public ChildObject child
{
get {
//if the chld hasnt been set already
if (_child == null)
{
//if the value of the integer has been set
if(some_val != null)
{
SomeMethod();
}
}
return _child;
}
set { _child = value;}
}
private void SomeMethod()
{
int new_val = this.some_val.Value + 5;
this.child = new ChildObject { some_val = new_val };
}