2014-01-11 36 views
0

我在解決方案中有兩個項目 - 一個是庫,另一個是主程序。 庫中某個類的構造函數創建了其他幾個對象。不幸的是,當我在主應用程序中調用該構造函數時,應該是看不見的。有什麼辦法解決這個問題嗎?來自另一個項目的構造函數

的,我說的是什麼例子:

namespace Library 
{     
     public class Foo 
     {  
      public Bar bar; 
      public Foo() 
      { 
       Bar bar = new Bar();  
      } 
     } 
} 



namespace Project1 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
       Foo foo = new Foo(); 
       //bar is not accessible here 
     } 
    } 
} 
+0

的創建者可以訪問此項目,因此缺少項目引用的聲音。 – usr

+4

你怎麼使用'Bar'?它只存在於構造函數中。它將在'Foo()'中創建,並且它不會被分配給任何'Foo'的成員,它將消失。 –

+0

我已經添加了參考。 – user3184801

回答

1

您需要將Bar對象分配到的Foo一些成員:

namespace Library 
{ 
    public class Bar 
    { 
     // whatever inside 
    } 

    public class Foo 
    {  
     public Bar BarMember { get; private set; } 

     public Foo() 
     { 
      BarMember = new Bar();  
     } 
    } 
} 



namespace Project1 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      Foo foo = new Foo(); 
      // foo.BarMember is accessible here 
     } 
    } 
} 

基本上是:

  • Bar物體mus t被分配到Foo的成員
  • 類別Bar需要在兩個項目的共同範圍內聲明 - 只需在Library內聲明它。它也必須是public - 在項目之間共享。
+0

對。愚蠢的錯誤。 – user3184801

1

你只是躲在你bar實例字段中Foo的構造函數,因爲你重新聲明bar作爲一個局部變量(你應該有一個編譯器警告有關)。

只是做到這一點:

namespace Library 
{     
    public class Foo 
    {  
      public Bar bar; 
      public Foo() 
      { 
       this.bar = new Bar();  
      } 
    } 
} 
1

問題是此行

Bar bar = new Bar();  

這是聲明名爲bar一個新的局部變量和分配新創建的值給它。這不會設置字段Foo.bar,因爲本地實際上會遮蔽該字段。爲了設置字段刪除聲明

bar = new Bar(); 

或者,如果你想成爲明確的,你可以使用this

this.bar = new Bar(); 

無論這將在現場設置Foo.bar爲新創造的價值。然後,Foo

相關問題