c# - 静态方法和访问变量的能力

标签 c# static

我正在尝试从静态方法访问变量。我了解静态方法与非静态方法的基本概念,但仍然不完全了解静态方法可以访问和不能访问的内容。

起初我试图将我的变量放在程序类的顶部,正如您从我的一些注释掉的行中看到的那样。我无法从我的静态方法访问它们,随着我对静态的了解越来越多,这变得有意义了。但是后来我将变量放在静态方法中。这是我不明白的。在静态方法中,我可以设置 fs = new FileStream(filename, FileMode.OpenOrCreate, FileAccess.Write, FileShare.ReadWrite); 但是一旦在 if 语句之外 sw = new StreamWriter(fs ) 当我在静态方法中有 FileStream fs 时给我一个错误。尝试将其设为静态,正如您在静态方法中的注释行所看到的那样,但这也不起作用。我似乎能够访问我的变量的唯一方法是在 Program 类中(在静态方法之外)将它们设为静态。

class Program {
    static FileStream fs;
    //   public bool fileopen = false;
    //  String filename = @"D:\Stock Trading\Test1.txt";
    static void Main(string[] args) {
        CreateDebugFile();
    }

    public static void CreateDebugFile() {
        StreamWriter sw;
        bool fileopen = false;
        //      static FileStream fs;
        String filename = @
        "D:\Stock Trading\Test1.txt";

        if (!fileopen) {
            fs = new FileStream(filename, FileMode.OpenOrCreate, FileAccess.Write, FileShare.ReadWrite);
            fileopen = true;
        }

        sw = new StreamWriter(fs);
        sw.Write("Current Bar" + "\t" + "time" + "\t" + "Open" + "\t" + "Close" + "\t" + "Low" + "\t" + "High");

    }
}

最佳答案

来自 MSDNstatic 关键字:

A non-static class can contain static methods, fields, properties, or events. The static member is callable on a class even when no instance of the class has been created. The static member is always accessed by the class name, not the instance name. Only one copy of a static member exists, regardless of how many instances of the class are created. Static methods and properties cannot access non-static fields and events in their containing type, and they cannot access an instance variable of any object unless it is explicitly passed in a method parameter.

It is more typical to declare a non-static class with some static members, than to declare an entire class as static. Two common uses of static fields are to keep a count of the number of objects that have been instantiated, or to store a value that must be shared among all instances. Static methods can be overloaded but not overridden, because they belong to the class, and not to any instance of the class. Although a field cannot be declared as static const, a const field is essentially static in its behavior. It belongs to the type, not to instances of the type. Therefore, const fields can be accessed by using the same ClassName.MemberName notation that is used for static fields. No object instance is required.

C# does not support static local variables (variables that are declared in method scope).

静态意味着它可以直接针对对象访问而无需创建实例,即 class ,因此可以像这样访问类 Name 中定义的静态成员 MyClassName : MyClassName.Name (而不是 new MyClassName().Name ),当您访问来自该类内部的静态成员,您可以只使用 Name,但编译器的处理方式与您从类外部访问它的方式类似。

虽然静态值未更改,但在应用程序中调用该静态属性的任何人都在访问同一个实例,如果可以从类外部更改该值,这可能会导致并发问题。

举个例子:

public class MyClassName
{
    public static string FilePath = @"C:\Temp";
    public static FileStream fs;

    public static void CreateFileStream()
    {
        //creates a file stream
    }
}

如果两个人同时调用同一个方法, MyClassName.CreateFileStream() 那么第一个进入的人创建一个文件流并将其设置为 fs ,然后第二个人创建一个文件流并将其设置为 fs ,现在它可能有人在类中引用了文件流,而另一个人可能持有对不再在类 MyClassName 上设置的原始文件流的引用。

因此,您需要注意如何公开静态成员(在您的特定示例中不是问题,但要牢记这一点很重要)。如果您声明了一个静态字段,您应该确保对其进行实例化或将其保留给类私有(private),这样您就可以确保它被实例化是为了使用它。

在您的情况下,您每次调用该方法时都会创建一个新的文件流,因为您的 bool fileopen 在方法内部,方法内部的任何内容都只能在该方法内部使用,无论是否是静态的,并且会再次创建每次调用该方法时,您需要在要从另一个静态字段、属性或方法调用的字段或属性或方法的每个声明中使用 static 关键字。

class Program {
    static FileStream fs;      //needs to be static
    public static bool fileopen = false;    //needs to be static
    static  String filename = @"D:\Stock Trading\Test1.txt"; 
             //needs to be static, or this one could also be 
             //const if it will never change

    static void Main(string[] args) {
        CreateDebugFile();
    }

public static void CreateDebugFile() {
    //...
    }
}

关于c# - 静态方法和访问变量的能力,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28846320/

相关文章:

c# - 事件触发的次数越来越多

c# - 隐藏和显示 TableLayoutPanel 的单元格

java - 如何将泛型类型 ArrayList 设为静态?

c++ - 静态之前的预期主要表达?常量指针必须使用

java - 访问父类子类中静态类的 protected 成员

c# - OwnerDraw 模式下的 ListBox DrawItem HotLight 状态?

c# - 实例化:将列表移动到参数中

c# - Neo4j 和参数化查询

java - 从静态 block 调用静态方法

C++ 静态虚拟成员?