C#让多个类共享另一个类的相同实例 [英] C# Let multiple class share the same instance of another class

查看:557
本文介绍了C#让多个类共享另一个类的相同实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么办法让多个类共享另一个类的相同实例?
因此,在我的C#程序中,我得到了三个类Gamelogic(A),FPSController(B)和SpawnPlayer(C)。

Is there any way to let multiple class share the same instance of another class? So in my c# program i've got three class Gamelogic(A), FPSController(B), and SpawnPlayer(C).

在我的情况下,类B和C将使用和更改A中的某些变量,以便使用我当前在两个不同类中实例化A的变量,然后使用点表示法可从A的实例访问变量,但问题是在实例化A的不同类之后,instance.variable的更改根本不会在B和C类之间共享。

In my case class B and C would use and alter some variables in A, in order to use the variables i'm currently instantiating A in two different classes and then use dot notation to access the variable from the instance of A, but the problem is that after A instantiated in different classes, the change in instance.variable does not share between B and C class at all.

静态类型是否可以解决此问题?或者写一个主线会更好。

Would static type be a good way of solving this? Or writing a main would be better.

任何建议将不胜感激。

Any suggestions would be appreciated.

推荐答案

有几种方法。这是一个:

There are a few ways. Here is one:

一种方法是依赖注入。
您可以将A的实例传递给B和C的构造函数(或传递给B和C的设置器/属性):

One way would be dependency injection. You can pass the instance of A along to the constructors of B and C (or to a setter/property of B and C):

A a = new A();
B b = new B(a);
C c = new C(a);

但是,这不允许您轻松更改两个对象中的A引用,这似乎是你的问题。
轻松更改引用的一种方法是将引用以某种方式包装在另一个对象中。

But this doesn't allow you to change the A reference in both objects easily, which seems to be your problem. One way to easily change the reference, is to wrap the reference in another object somehow.

一个好的方法是创建一个Context对象。并将该上下文对象传递给B和C而不是传递A。该上下文对象充当我们的包装器。如果需要在多个变量之间共享(共享/全局状态),则上下文对象会变得更加有用-请参见上下文模式。示例:

A nice way to do this could be to create a Context object and pass that context object along to B and C instead of passing A. The context object plays the role as our wrapper. A context object becomes more useful if multiple variables needs to be shared between them (the shared/global state) - see the "Context pattern". Example:

public class Context {
    public A a;
    public ...other state you want to share...;

    public Context(A a) { this.a = a; ... }
}

...

A a = new A();

Context context = new Context(a,...);

B b = new B(context);
C c = new C(context);

根据您的情况,可以使用静态变量。 (或单例)

Depending on your situation, a static variable might be fine, however. (Or a singleton)

(在某些情况下,将A实例传递给B和C的方法,而不是传递给它们的构造函数,可能会更好-然后它们还总是获取a的当前版本(并且可能更线程安全)

(In some cases passing the A-instance along to the methods of B and C, rather than to their constructor, might be better - then they also always get the current version of a (and might be more thread-safe))

这篇关于C#让多个类共享另一个类的相同实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆