C#中静态变量有什么用?什么时候使用?为什么我不能在方法中声明静态变量?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10795502/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is the use of static variable in C#? When to use it? Why can't I declare the static variable inside method?
提问by Kartik Patel
I have searched about static variables in C#, but I am still not getting what its use is. Also, if I try to declare the variable inside the method it will not give me the permission to do this. Why?
我已经在 C# 中搜索了静态变量,但我仍然不知道它的用途是什么。此外,如果我尝试在方法中声明变量,它不会授予我执行此操作的权限。为什么?
I have seen some examples about the static variables. I've seen that we don't need to create an instance of the class to access the variable, but that is not enough to understand what its use is and when to use it.
我看过一些关于静态变量的例子。我已经看到我们不需要创建类的实例来访问变量,但这还不足以了解它的用途以及何时使用它。
Second thing
第二件事
class Book
{
public static int myInt = 0;
}
public class Exercise
{
static void Main()
{
Book book = new Book();
Console.WriteLine(book.myInt); // Shows error. Why does it show me error?
// Can't I access the static variable
// by making the instance of a class?
Console.ReadKey();
}
}
采纳答案by Kartik Patel
A staticvariable shares the value of it among all instances of the class.
一个static变量在类的所有实例之间共享它的值。
Example without declaring it static:
没有将其声明为静态的示例:
public class Variable
{
public int i = 5;
public void test()
{
i = i + 5;
Console.WriteLine(i);
}
}
public class Exercise
{
static void Main()
{
Variable var = new Variable();
var.test();
Variable var1 = new Variable();
var1.test();
Console.ReadKey();
}
}
Explanation: If you look at the above example, I just declare the intvariable. When I run this code the output will be 10and 10. Its simple.
解释:如果你看上面的例子,我只是声明了int变量。当我运行此代码时,输出将是10和10。这很简单。
Now let's look at the static variable here; I am declaring the variable as a static.
现在让我们看看这里的静态变量;我将变量声明为static.
Example with static variable:
静态变量示例:
public class Variable
{
public static int i = 5;
public void test()
{
i = i + 5;
Console.WriteLine(i);
}
}
public class Exercise
{
static void Main()
{
Variable var = new Variable();
var.test();
Variable var1 = new Variable();
var1.test();
Console.ReadKey();
}
}
Now when I run above code, the output will be 10and 15. So the static variable value is shared among all instances of that class.
现在,当我运行上面的代码时,输出将是10和15。因此静态变量值在该类的所有实例之间共享。
回答by Pranay Rana
static variables are used when only one copy of the variable is required. so if you declare variable inside the method there is no use of such variable it's become local to function only..
当只需要一个变量副本时,使用静态变量。因此,如果您在方法中声明变量,则不会使用此类变量,它只会成为局部函数。
example of static is
静态的例子是
class myclass
{
public static int a = 0;
}
Variables declared static are commonly shared across all instances of a class.
声明为静态的变量通常在类的所有实例之间共享。
Variables declared static are commonly shared across all instances of a class. When you create multiple instances of VariableTest class This variable permanent is shared across all of them. Thus, at any given point of time, there will be only one string value contained in the permanent variable.
声明为静态的变量通常在类的所有实例之间共享。当您创建 VariableTest 类的多个实例时,此变量永久在所有实例之间共享。因此,在任何给定的时间点,永久变量中将只包含一个字符串值。
Since there is only one copy of the variable available for all instances, the code this.permament will result in compilation errors because it can be recalled that this.variablename refers to the instance variable name. Thus, static variables are to be accessed directly, as indicated in the code.
由于所有实例只有一份变量可用,因此代码 this.permament 会导致编译错误,因为可以回忆一下 this.variablename 指的是实例变量名称。因此,如代码所示,将直接访问静态变量。
回答by dowhilefor
Some "real world" examples for static variables:
静态变量的一些“真实世界”示例:
building a class where you can reach hardcoded values for your application. Similar to an enumeration, but with more flexibility on the datatype.
构建一个类,您可以在其中获取应用程序的硬编码值。类似于枚举,但在数据类型上具有更大的灵活性。
public static class Enemies
{
public readonly static Guid Orc = new Guid("{937C145C-D432-4DE2-A08D-6AC6E7F2732C}");
}
The widely known singleton, this allows to control to have exactly one instance of a class. This is very useful if you want access to it in your whole application, but not pass it to every class just to allow this class to use it.
广为人知的单例,这允许控制一个类的一个实例。如果您想在整个应用程序中访问它,而不是将它传递给每个类只是为了让这个类使用它,这将非常有用。
public sealed class TextureManager
{
private TextureManager() {}
public string LoadTexture(string aPath);
private static TextureManager sInstance = new TextureManager();
public static TextureManager Instance
{
get { return sInstance; }
}
}
and this is how you would call the texturemanager
这就是你如何调用纹理管理器
TextureManager.Instance.LoadTexture("myImage.png");
About your last question: You are refering to compiler error CS0176. I tried to find more infor about that, but could only find what the msdn had to say about it:
关于您的最后一个问题:您指的是编译器错误CS0176。我试图找到更多关于它的信息,但只能找到 msdn 不得不说的内容:
A static method, field, property, or event is callable on a class even when no instance of the class has been created. If any instances of the class are created, they cannot be used to access the static member. Only one copy of static fields and events exists, and static methods and properties can only access static fields and static events.
即使没有创建类的实例,静态方法、字段、属性或事件也可以在类上调用。如果创建了类的任何实例,则它们不能用于访问静态成员。静态字段和事件只存在一份副本,静态方法和属性只能访问静态字段和静态事件。
回答by Dennis
C# haven't static variablesat all. You can declare static fieldin the particular type definition via C#. Static field is a state, shared with all instances of particular type. Hence, the scope of the static field is entire type. That's why you can't declare static fieldwithin a method - method is a scope itself, and items declared in a method must be inaccessible over the method's border.
C# 根本没有静态变量。您可以通过 C# 在特定类型定义中声明静态字段。静态字段是一种状态,与特定类型的所有实例共享。因此,静态字段的范围是整个类型。这就是为什么您不能在方法中声明静态字段的原因- 方法本身就是一个范围,并且在方法中声明的项目必须无法通过方法的边界访问。
回答by MichaelY
The data members and function members that operate on the instance of the type are called instance members. The int's ToString method (for example) are examples of instance members. By default, members are instance members. Data members and function members that don't operate on the instance of the type, but rather on the type itself, must be marked as static. The Test.Main and Console.WriteLine methods are static methods. The Console class is actually a static class, which means all its members are static. You never actually create instances of a Console—one console is shared across the whole application.
对类型的实例进行操作的数据成员和函数成员称为实例成员。int 的 ToString 方法(例如)是实例成员的示例。默认情况下,成员是实例成员。不对类型的实例进行操作,而是对类型本身进行操作的数据成员和函数成员必须标记为静态。Test.Main 和 Console.WriteLine 方法是静态方法。Console 类实际上是一个静态类,这意味着它的所有成员都是静态的。您实际上从未创建过控制台的实例——整个应用程序共享一个控制台。
回答by Arnold Parge
Try calling it directly with class name Book.myInt
尝试使用类名直接调用它 Book.myInt
回答by Kunal Mukherjee
Static classes don't require you to create an object of that class/instantiate them, you can prefix the C# keyword static in front of the class name, to make it static.
静态类不需要您创建该类的对象/实例化它们,您可以在类名前面添加 C# 关键字 static 的前缀,使其成为静态的。
Remember: we're not instantiating the Console class, String class, Array Class.
请记住:我们没有实例化 Console 类、String 类、Array 类。
class Book
{
public static int myInt = 0;
}
public class Exercise
{
static void Main()
{
Book book = new Book();
//Use the class name directly to call the property myInt,
//don't use the object to access the value of property myInt
Console.WriteLine(Book.myInt);
Console.ReadKey();
}
}
回答by Md Shahriar
Static variable retains it's previous value until the program exit. Static is used by calling directly class_Name.Method() or class_Name.Property. No object reference is needed. The most popular use of static is C#'s Math class. Math.Sin(), Math.Cos(), Math.Sqrt().
静态变量保留其先前的值,直到程序退出。通过直接调用 class_Name.Method() 或 class_Name.Property 来使用静态。不需要对象引用。静态最流行的用法是 C# 的 Math 类。Math.Sin()、Math.Cos()、Math.Sqrt()。
回答by JohnRC
In response to the "when to use it?" question:
回应“什么时候使用它?” 题:
I often use a static (class) variable to assign a unique instance ID to every instance of a class. I use the same code in every class, it is very simple:
我经常使用静态(类)变量为类的每个实例分配一个唯一的实例 ID。我在每个类中都使用相同的代码,很简单:
//Instance ID ----------------------------------------
// Class variable holding the last assigned IID
private static int xID = 0;
// Lock to make threadsafe (can omit if single-threaded)
private static object xIDLock = new object();
// Private class method to return the next unique IID
// - accessible only to instances of the class
private static int NextIID()
{
lock (xIDLock) { return ++xID; }
}
// Public class method to report the last IID used
// (i.e. the number of instances created)
public static int LastIID() { return xID; }
// Instance readonly property containing the unique instance ID
public readonly int IID = NextIID();
//-----------------------------------------------------
This illustrates a couple of points about static variables and methods:
这说明了关于静态变量和方法的几点:
- Static variables and methods are associated with the class, not any specific instance of the class.
- A static method can be called in the constructor of an instance - in this case, the static method NextIID is used to initialize the readonly property IID, which is the unique ID for this instance.
- 静态变量和方法与类相关联,而不是与类的任何特定实例相关联。
- 可以在实例的构造函数中调用静态方法——在这种情况下,静态方法 NextIID 用于初始化只读属性 IID,这是该实例的唯一 ID。
I find this useful because I develop applications in which swarms of objects are used and it is good to be able to track how many have been created, and to track/query individual instances.
我发现这很有用,因为我开发的应用程序中使用了成群的对象,并且能够跟踪已创建的对象数量以及跟踪/查询单个实例是很好的。
I also use class variables to track things like totals and averages of properties of the instances which can be reported in real time. I think the class is a good place to keep summary information about all the instances of the class.
我还使用类变量来跟踪可以实时报告的实例属性的总数和平均值等内容。我认为该类是保存有关该类所有实例的摘要信息的好地方。
回答by pratham gn
On comparison with session variables, static variables will have same value for all users considering i am using an application that is deployed in server. If two users accessing the same page of an application then the static variable will hold the latest value and the same value will be supplied to both the users unlike session variables that is different for each user. So, if you want something common and same for all users including the values that are supposed to be used along the application code then only use static.
与会话变量相比,考虑到我使用的是部署在服务器中的应用程序,静态变量对所有用户都具有相同的值。如果两个用户访问应用程序的同一页面,则静态变量将保存最新值,并且将向两个用户提供相同的值,这与每个用户不同的会话变量不同。因此,如果您想要所有用户都通用且相同的东西,包括应该在应用程序代码中使用的值,那么只使用静态。

