在c#中创建一个类

jay*_*t55 -1 c# class winforms

我已经阅读了文档和一切,但我很困惑.我以前从来不需要创建一个类,现在我也是.

我希望有类似的东西:

TextDocument.Save("filepath", "contents of file to save");
Run Code Online (Sandbox Code Playgroud)

和类似的东西:

Application.Create("filepath", "text/code to save");
Run Code Online (Sandbox Code Playgroud)

和:

Stylesheet.Save("filepath", "contents");
Run Code Online (Sandbox Code Playgroud)

并将它们放在一个类中并为它们创建方法但是我很困惑如何去做它可以有人请帮我这个吗?

谢谢,jase

Mar*_*ell 10

没有更多代码就不可能说,但那些看起来像静态方法,即创建一个新的类(cs)文件,并添加如下内容:

using System.IO;
public class TextDocument {
   public static void Save(string path, string contents) {
       File.WriteAllText(path, contents);
   }
}
Run Code Online (Sandbox Code Playgroud)

如果TextDocument实际上是一个实例,请删掉这个词static.

请注意,要进行可调用,您还需要了解名称空间.以上是在默认命名空间中,但这有点粗俗.它应该更像是:

using System.IO;
namespace FooCorp.MagicApp {
    public class TextDocument {
        public static void Save(string path, string contents) {
            File.WriteAllText(path, contents);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

然后只有代码using FooCorp.MagicApp会看到你的类(这是保持理智的好东西; .NET框架中有很多类)

  • 你可以 - 他们被称为书籍;-) (11认同)