2014-06-25 57 views
-1

我有一个具有B类集合的类A.是否可以从该集合中的类B的实例访问类A?我可以访问拥有该集合中的集合的类吗?

Class A 
{ 
    public string Something { get; set; } 
    List<B> collection = new List<b>(); 
    public void Add(B b) 
    { 
     collection.Add(b); 
    } 
} 

Class B 
{ 
    public int Num { get; set; } 
} 

static void Main(string[] args) 
{ 
    B b = new B(); 
    b.Num = 5; 

    A a = new A(); 
    a.Something = "Hello"; 
    a.Add(b); 
} 

有没有什么办法来访问字符串a.Something from object b?

+3

不,你不能... –

+0

你为什么要这样做? – Montaldo

回答

0

B将需要包含引用到其容器A.所以,某事像:

Class B 
{ 
    public int Num { get; set; } 
    public A Container { get; set; } 
} 

然后在Add()方法中的一个:

public void Add(B b) 
{ 
     collection.Add(b); 
     b.Container = this; 
} 

这是假设B只能被添加到A的单个实例中,否则你需要使用一个集合(例如List)并相应地在Add/Remove上进行更新。

-1

Is there any way to access string a.Something from object b?

NO。你不能。

+0

任何downvoter照顾评论? –

+0

我没有降低它的效果,但尽管如上所述,他们有自己的问题,但这个问题有解决方案。 – user3613916

0

随着下列变化,它是可能的;但应该警告,它根本没有意义。

Class A 
{ 
    public string Something { get; set; } 
    List<B> collection = new List<b>(); 
    public void Add(B b) 
    { 
     b.Master = this; 
     collection.Add(b);   
    } 
} 

Class B 
{ 
    public A Master {get; set;} 
    public int Num { get; set; } 
} 

static void Main(string[] args) 
{ 
    B b = new B(); 
    b.Num = 5; 

    A a = new A(); 
    a.Something = "Hello"; 
    a.Add(b); 
    Console.Writeline(b.Master.Something); 
} 
+0

我也是首先讨论这个解决方案,但它很有缺陷。考虑创建两个'A'对象并为它们中的每一个添加一个'B'对象。在这种情况下,'B'只能保持最后添加的引用。所以你要么需要'List Masters'或重新考虑应用程序的设计并从'A'访问'Something'。我甚至都不想去除'B'情景 –

相关问题