如何在类范围内使用依赖项?

时间:2018-07-24 17:26:36

标签: c#

我想使用我在类范围中下载的依赖项。该代码有效:

using System;
using System.IO;
using System.Collections;

namespace PrintFilesToConsole
{
    class Preprogram
    {
        public void Main2()
        {
            IEnumerable myDirs = System.IO.Directory.EnumerateDirectories("/Users/Eunice/Desktop");
            Console.WriteLine("Hello World!");
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Preprogram preprogram = new Preprogram();
            preprogram.Main2();
        }
    }


}

但是当我写

System.IO.Directory.EnumerateDirectories
("/Users/Eunice/Desktop");

函数

之外
Main2

,进入类的范围

 Preprogram

,计算机提示该功能在当前上下文中不存在

除非我将返回值分配给变量,如

IEnumerable myDirs = System.IO.Directory.EnumerateDirectories("/Users/Eunice/Desktop");
enter code here

1 个答案:

答案 0 :(得分:0)

让我们简化您的示例以说明问题所在。


我们有一个类A,其中包含方法DoSomething

public class A
{
    public int DoSomething()
    {
        return 42;
    }
}

可以说它还包含方法MakeStuff,该方法调用DoStuff方法:

public class A
{
    public int DoSomething()
    {
        return 42;
    }

    public void MakeStuff()
    {
        int x = this.DoSomething();
        // We called the method DoSomething, which returns 42, and now x equals 42.
    }
}

我们在MakeStuff中所做的是调用方法,并将返回值分配给了局部变量


我们还可以在类A中放置一个字段(或属性):

public class A
{
    private int y;

    ...
}

,我们甚至可以为该字段分配默认值

public class A
{
    private int y = 10;

    ...
}

该值不必硬编码:我们也可以使用函数的返回值,就像我们在MakeStuff中所做的一样将返回值分配给局部变量时的方法:

public class A
{
    private int y = this.DoSomething();

    // Now y equals 42, because DoSomething() returns 42.
    ...
}

如果我们放弃返回值,例如,我们不能在方法之外调用函数。我们不能这样做:

public class A
{
    this.DoSomething();

    // This will not compile!
}

我希望这个简单的例子能说明您为什么得到所描述的错误。我试图使它尽可能简单-但是,如果您不理解答案的一部分或任何内容,请随时评论您需要帮助的地方,我们将尽最大努力为您提供帮助。

相关问题