2012-08-16 192 views
-4

可能重复:
Why Would I Ever Need to Use C# Nested Classes访问嵌套类

我正在做的矮个子,我有一个类,它看起来像这样:

namespace Blub { 
    public class ClassTest { 
     public void teest() { 
      return "test"; 
     } 

     public class AnotherTest { 
      public void blub() { 
       return "test"; 
      } 
     } 
    } 
} 

我可以可以像这样访问称为“teest”的函数,但是如何在不做另一个“新ClassTest.Another”的情况下访问函数“blub”测试()”?

访问的功能teest:

Blub.ClassTest = new Blub.ClassTest(); 
ClassTest.teest(); //test will be returned 

我尝试(我怎么想,就AnotherTest访问是这样的:

Blub.ClassTest = new Blub.ClassTest(); 
ClassTest.blub(); //test will be returned 

哪个不工作,我可以访问AnotherTest这样,我不想要它:

Blub.ClassTest2 = new Blub.ClassTest.AnotherTest(); 
ClassTest.blub(); //test will be returned 

有人知道这个解决方案吗?

+2

一个相关的问题是下面的,应在了解嵌套类的好处帮助:http://stackoverflow.com/questions/1083032/why -would-i-ever-need-to-use-c-sharp-nested-class有效地,通过嵌套一个类,你正在做出一个关于何时构建该类以及谁有权访问它的设计决策。 – dash 2012-08-16 17:41:02

回答

2

你声明AnotherTestClassTest,这就是为什么你必须浏览它使用namespace.class.2ndClass了。

但是,我想你对OO概念并不是很了解,对吗?如果您声明一个类中的方法,它只能提供类的对象,除非你把它声明为static,什么意思,这将是一个类方法而非实例方法

如果你想ClassTest有2种方法(teestblub)只需在类的主体同时声明,如:

public class ClassTest 
{ 
    public string teest() 
    { 
     return "test"; 
    } 


    public string blub() 
    { 
     return "test"; 
    } 
} 

而且,请注意,如果一个方法声明为void它赢得” t返回任何东西(实际上,我认为你的原始代码甚至不会编译)。

我建议你在尝试自己弄清楚之前先研究OO。

0

如果您需要访问其他课程,则必须将其设置为第一课程中的一个属性。

namespace Blub { 
    public class AnotherTest { 
     public void blub() { 
      return "test"; 
     } 
    } 


    public class ClassTest { 
    public AnotherTest at = new AnotherTest(); 
    public void teest() { 
     return "test"; 
    } 


    } 
} 

然后访问它是这样的:

ClassTest x = new ClassTest(); 
x.at.blub();