C# 为什么双向组合不适合传递值类型?
我只有两门课:C# 为什么双向组合不适合传递值类型?,c#,composition,C#,Composition,我只有两门课: class A { public B b = new B(); public bool flag {get; set;} } class B { public void foo() { //iterates a dataTable with column "someBoolCondition" // I want to set A's bool to true, after the first record that has 'true
class A
{
public B b = new B();
public bool flag {get; set;}
}
class B
{
public void foo()
{
//iterates a dataTable with column "someBoolCondition"
// I want to set A's bool to true, after the first record that has 'true' in column
//"someBoolCondition". Thus is thought to avoid bool memebers in each class.
}
}
我的想法没有布尔的价值观那么好:
我认为这是一个问题,因为我看到行“ReferenceToA.flag=true;”被执行,但后来我没有看到a的标志变为true(保持为false)。为什么会这样?
class A
{
public bool flag {get; set;}
public B b = new B();
b.ReferenceToA = this;
}
class B
{
public A ReferenceToA {get; set}
public void foo()
{
ReferenceToA.flag = true; //...
}
}
对于引用类型的成员,有没有一种优雅的方法可以做到这一点?
这是一种过度的杀伤力,应该采取不同的做法吗?与任何参考类型相比,你的传球模式实际上并不差——完全相同
实际上,引用的大小(通过值传递)是32位或64位。这也是bool的大小,这绝对不是一个过分的举动。可能有其他方法可以实现您在这里所做的事情,但选择其中一种取决于您的项目需求。 对我来说,这绝对没问题
为了简化,您可以考虑将布尔属性
设置为static
,这样您就可以直接从B类A.flag
访问它。但我很难说,在这种情况下,仅仅通过阅读您的帖子,这是否真的适合您。我不明白您为什么说bool与参考类型之间存在问题。引用是32位或64位,bool占用相同的内存-因此没有区别。我看到行“ReferenceToA.flag=true;”被执行,但后来我没有看到A的标志变为true(保持false)。为什么会这样?我看到行“ReferenceToA.flag=true;”被执行,但后来我没有看到A的标志变为true(保持为false)。为什么呢?