【问题标题】:Accessing a Nested Class [duplicate]访问嵌套类 [重复]
【发布时间】:2012-08-13 02:55:25
【问题描述】:

可能重复:
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”的函数,但是如何在不执行另一个“new ClassTest.AnotherTest()”的情况下访问函数“blub”?

访问功能测试:

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

有人知道解决方案吗?

【问题讨论】:

  • 一个相关的问题如下,它应该有助于理解嵌套类的好处:stackoverflow.com/questions/1083032/… 实际上,通过嵌套一个类,您正在做出关于何时构建的设计决策该类以及谁可以访问它。

标签: c#


【解决方案1】:

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

但是,我想您不太了解 OO 概念,是吗?如果你在一个类中声明一个方法,它只会对那个类的对象可用,除非你声明为static,这意味着它是一个类方法 而不是实例方法

如果您希望 ClassTest 有 2 个方法(teestblub),只需在类的主体中声明这两个方法,例如:

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


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

另外,请注意,如果一个方法被声明为void,它不会返回任何东西(事实上,我认为您的原始代码甚至根本无法编译)。

我建议您先深入研究 OO,然后再尝试自己解决问题。

【讨论】:

    【解决方案2】:

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

    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();
    

    【讨论】:

      猜你喜欢
      • 2017-11-12
      • 2010-11-09
      • 2015-11-16
      • 2017-01-05
      • 1970-01-01
      • 1970-01-01
      • 2019-03-12
      • 2021-04-04
      • 2017-07-06
      相关资源
      最近更新 更多