开发者

why does bi-directional composition is not good to pass a value type?

I have only 2 classes:

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开发者_Python百科, after the first record that has 'true' in column
   //"someBoolCondition". Thus is thought to avoid bool memebers in each class.
  }
}

My idea, wasn't so good as bool is of value type: I think it's a problem because I see the line "ReferenceToA.flag = true;" is executed but later I don't see A's flag turns into true (stays false). Why is that?

   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; //...
         }
    }

Is there an elegant way to do it like as for member of reference type? Is it an overkill and should be done differently ?


Your pattern is actually not worse when passing bool compared to any reference type - it's exactly the same.

Indeed the size of the reference (which is passed by value) is 32 or 64 bit. That's also the size of bool.


This is not a overkill definitely. May be there are other ways to achieve what you're doing here, but chose one or another depends on you project requirements. For me it's absolutely ok.

For simplifying you can think of making boolean property static, so you can access it from B class directly A.flag. But it's hard to say to me, if this is really suitable solution to you in this case by just reading your post.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜