找到你要的答案

Q:Is it possible to have different value of static variable for every instance?

Q:是否有可能为每个实例提供不同的静态变量值?

I have a class with some static variables and I want to create multiple independent instances of this class. Independent meaning, that they do not share values of these static variables.

Is there a way how to achieve this without refactoring said class?

我有一些静态变量的类,我想创建这个类的多个独立的实例。独立意义,即它们不共享这些静态变量的值。

有没有办法实现这一点,而不重构说的类?

answer1: 回答1:

I have a class with some static variables and I want to create multiple independent instances of this class.

In that case you just don't want static variables. static means "associated with the type rather than an instance of the type" - you just want instance variables.

That may mean changes elsewhere in your app, of course, but there's nothing you can do about that - or at least, any alternatives are going to be much more hacky than just taking the straightforward approach.

我有一些静态变量的类,我想创建这个类的多个独立的实例。

在这种情况下,你只是不希望静态变量。静态意思是“与类型关联而不是类型的实例”--你只需要实例变量。

这可能意味着在你的应用程序,其他地方的变化,当然,但有什么可以做的,或者至少,任何选择都要比只是以简单的方法更容易的多。

answer2: 回答2:

Static variables are shared among every instance of a type, so you need instance variables, that will solve your problem. so refactoring is needed.

静态变量在一个类型的每个实例中共享,所以你需要实例变量来解决你的问题。所以需要重构。

c#  .net