C# 私有、静态和只读

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/968132/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 04:27:31  来源:igfitidea点击:

C# private, static, and readonly

c#log4netaccess-modifiers

提问by ant2009

I was reviewing some code for log4net and I came across this.

我正在 log4net 的一些代码,但我遇到了这个问题。

private static readonly ILog logger = LogManager.GetLogger(typeof(AdminClient));

I am wondering why would you need to have private static readonly.

我想知道为什么您需要只读私有静态。

From my understanding private would mean that the variable cannot not be used outside the class unless there is a accessor method or get property.

根据我的理解,private 意味着该变量不能在类外使用,除非有访问器方法或 get 属性。

static would mean that the variable is scoped only in this file only.

static 意味着该变量仅在此文件中起作用。

readonly would mean that you can only read from the value and cannot assign it.

readonly 意味着您只能从值中读取而不能分配它。

So, I am thinking that the person who wrote this code. declared it private as they don't want it used outside the class and static so that don't want it used outside the file. However, if there is a get property would static prevent this form happening.

所以,我在想写这段代码的人。将其声明为私有,因为他们不希望在类和静态之外使用它,因此不希望在文件之外使用它。但是,如果有一个 get 属性会静态阻止这种形式的发生。

I think I can understand readonly and the value is only to be read from and not set.

我想我可以理解 readonly 并且该值只能读取而不是设置。

Many thanks for any advice,

非常感谢您的任何建议,

采纳答案by victor hugo

  • privateNo one should use the logger field outside the class (even in subclasses), if you don't set this any other class could use your logger for log in your class' name.
  • staticThe attribute is attachedto the class so it won't repeatwith each instance of the class. If you don't set this the logger attribute will occupy extra space in memory with every instance the system makes of the object (you misunderstood this).
  • readonlyThe logger field shouldn't be modified.
  • private没有人应该在类之外(甚至在子类中)使用 logger 字段,如果你不设置这个,任何其他类都可以使用你的 logger 来登录你的类名。
  • static属性附加到类,因此它不会与类的每个实例重复。如果你不设置这个,记录器属性将在系统为对象创建的每个实例中占用额外的内存空间(你误解了这一点)。
  • readonly不应修改记录器字段。

回答by Tal Pressman

static does notmean that it cannot be accessed from other files - this isn't C. The static keyword means that the logger object is a class variable instead of an instance variable, so even when accessed from different objects of that class, they will all refer to the same logger object.

静态不意味着它不能从其他文件被访问-从该类的不同的对象进行访问时,这不是C. static关键字意味着记录器对象是类变量,而不是一个实例变量,因此,即使,它们将都指向同一个记录器对象。

回答by Stefan Mai

I think you're misunderstanding static. Static doesn't mean "can't be used outside the file." Static means: there's one per class. What this declaration does is creates a logger that is only allocated once (static), only available in the class (not in derived classes either) (private), and cannot be written to past its initialization (readonly).

我认为你误解了静态。静态并不意味着“不能在文件外使用”。静态意味着:每个班级都有一个。这个声明的作用是创建一个仅分配一次(静态)的记录器,仅在类中可用(也不在派生类中)(私有),并且不能在其初始化之后写入(只读)。

Good question though!

好问题!

回答by Robert

static in c# means the member is associated with the class, and not with an instance of the class. Readonly is important because in c# most variables, and this one in particular, are reference variables. The readonly means that this variable will always reference the same logger.

c# 中的静态表示成员与类相关联,而不是与类的实例相关联。Readonly 很重要,因为在 c# 中,大多数变量,尤其是这个变量,都是引用变量。readonly 意味着这个变量将始终引用同一个记录器。

回答by Robert

A readonlyvariable is very much like const in that the value is constant throughout its lifetime. The difference is that a readonly variable is initialized at run-time and const is at compile time. Static, in sort of laymen terms, means that the instance of the variable does not depend on the instance of the object it is declared in. Its lifetime persists from function call to function call. A static variable is faster to access because its storage remains allocated for the entire duration of the program. So knowing this we can go back to your question.

一个只读变量很像,该值是在其整个生命周期不变常量。区别在于 readonly 变量在运行时初始化,而 const 在编译时初始化。用外行人的话说,静态意味着变量的实例不依赖于声明它的对象的实例。它的生命周期从一个函数调用到另一个函数调用。静态变量的访问速度更快,因为它的存储空间在程序的整个持续时间内都处于分配状态。所以知道了这一点,我们可以回到你的问题。

Why is 'logger' a static member? That's a design decision. I need to know how you're using it to answer this question. Why is it readonly? Because it seems like it's initialized once and its instance is used throughout. We can make sure that nobody else tampers with the value of logger by making it 'read-only' right after we initialize it.

为什么“记录器”是静态成员?这是一个设计决定。我需要知道你是如何使用它来回答这个问题的。为什么是只读的?因为它似乎被初始化了一次并且它的实例在整个过程中被使用。我们可以通过在初始化后立即将其设置为“只读”来确保没有其他人篡改 logger 的值。

回答by Colin Desmond

What the developer is saying is that when they call logger.Info(...) in any instance of this class they want to use a common (static) instance (so don't need to create a new logger per class instance), they want to be certain that it hasn't changed since it was created (readonly) and if we are in virtual function in a derived class then I want to make sure I don't use the base class one by mistake (private).

开发人员所说的是,当他们在此类的任何实例中调用 logger.Info(...) 时,他们希望使用公共(静态)实例(因此不需要为每个类实例创建一个新的记录器),他们想确定它自创建以来没有改变(只读),如果我们在派生类的虚函数中,那么我想确保我不会错误地使用基类(私有)。

回答by Noam Gal

The reason to put a readonly flag on a private variable is to declare that the variable will always reference the same object. It's true that being private makes it invisible to anyone outside the class, but this way we can make sure we didn't accidentaly overwrite the variable with a new object, by writing something like

在私有变量上放置只读标志的原因是声明该变量将始终引用同一个对象。确实,私有使得类之外的任何人都看不到它,但是这样我们可以确保我们不会意外地用新对象覆盖变量,通过编写类似的东西

logger = LogManager.GetLogger(typeof(AdminClient));

somewhere else in our class. With readonly it just won't compile (Unless it was not initialized before, andwe are in the (static) constructor)

在我们班的其他地方。使用 readonly 它不会编译(除非它之前没有初始化,并且我们在(静态)构造函数中)

回答by Noam Gal

Static variables falls in category of "class variables", a class variable is one that are associated with class instead of class object, on the other hand instance variables are variables that are associted with class object means each time a class object is intialized this object will have its own copy of that "Instance Variable" (non static) while static variable is shared among all objects of classes in running program like size of linked list etc. readonly is c# keyword that is used to make a variable readonly, java doesnt provide such facility you have to write a public method to access variables you dont wanna get tempered.

静态变量属于“类变量”的范畴,类变量是与类而不是类对象相关联的变量,另一方面,实例变量是与类对象相关联的变量,意味着每次类对象初始化此对象时将拥有自己的“实例变量”(非静态)副本,而静态变量在运行程序中的所有类对象之间共享,例如链表的大小等。 readonly 是 c# 关键字,用于使变量只读,java 没有提供这样的设施,您必须编写一个公共方法来访问您不想受到限制的变量。

回答by jpdedmon

Sorry, I know this has already been answered and it's really old, but I wanted to let anyone who comes across this article know that this is how you set up a "Singleton" pattern. Anyone who wants to know more about the code example in the question will likely benefit from learning more about Singletons and how they are used (mediators, loggers, async callbacks, etc.).

抱歉,我知道这已经有人回答了,而且真的很旧,但我想让任何看到这篇文章的人都知道,这就是您设置“单例”模式的方式。任何想了解更多关于问题中的代码示例的人都可能会从更多地了解单例及其使用方式(中介器、记录器、异步回调等)中受益。

// mothership stuff about singletons
http://msdn.microsoft.com/en-us/library/ff650316.aspx
http://msdn.microsoft.com/en-us/library/ff650849.aspx

// 关于单身人士的母爱
http://msdn.microsoft.com/en-us/library/ff650316.aspx
http://msdn.microsoft.com/en-us/library/ff650849.aspx

// a great SO discussion about them
What is so bad about singletons?

// 关于它们的一个很好的 SO 讨论
单身人士有什么不好?