我可以访问内部类的外部类对象 [英] Can i access outer class objects in inner class

查看:122
本文介绍了我可以访问内部类的外部类对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的三个类。

  class A 
{
public class innerB
{
//做某事
}

public class innerC
{
//尝试在这里直接或间接访问objB。
//我不必创建一个innerB的对象,而是访问由A
//i.e创建的对象。
innerB objInnerB = objB;
//不喜欢这个
innerB objInnerB = new innerB();
}

private innerB objB {get; set;} ** //私人**

public A()
{
objB = new innerB();
}
}

我想在类中访问B类的对象C是由类A创建的。
可以以某种方式对类C中的类A进行更改。可以通过创建事件或任何方式获得A类对象。



编辑:我提出上述问题的错误。在A中创建的对象是私人不公开



可以通过创建事件进行此操作


解决方案

如果无论如何我可以提出一个可以由A类处理的事件,那么我的问题可以解决。 p>如果我正在正确阅读你想要访问innerC中的类A的objB属性,而不传递它。



这不是C#内部类的工作方式,如本文所述: C#嵌套类就像C ++嵌套类而不是Java内部类



如果要从innerC访问A.objB,那么您将要以某种方式将A类传递给innerC AND 确保您以某种方式公开objB属性。 (即如果您将objB设置为私有,则此操作将不起作用。)


I have three classes like this.

class A
{
    public class innerB
       {
       //Do something
       }

    public class innerC
       {
        //trying to access objB here directly or indirectly over here. 
        //I dont have to create an object of innerB, but to access the object created by A
        //i.e.
             innerB objInnerB = objB;
        //not like this
             innerB objInnerB= new innerB();
       }

private innerB objB{get;set;}  **//Private**

public A()
   {
    objB= new innerB();
   }
}

I want to access the object of class B in Class C that is created by class A. Is it possible somehow to make changes on object of Class A in Class C. Can i get Class A's object by creating event or anyhow.

Edit: My mistake in asking the question above. Object of B created in A is private not public

IS IT POSSIBLE TO DO THIS BY CREATING EVENT

If anyhow I become able to raise an event that can be handled by Class A, then my problem can be solved.

解决方案

If I'm reading you correctly you want to access the objB property of class A within innerC WITHOUT passing it along.

This isn't how C# inner classes work, as described in this article: C# nested classes are like C++ nested classes, not Java inner classes

If you want to access A.objB from innerC then you are going to have to somehow pass class A to innerC AND make sure that you expose the objB property somehow. (i.e. this won't work if you have objB set to private.)

这篇关于我可以访问内部类的外部类对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆