可以在多个类之间共享的对象 [英] objects that can be shared across multiple classes

查看:49
本文介绍了可以在多个类之间共享的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


我有一个包含11个课程的项目.现在,每个类都引用任务层(另一组多个类),并且每次都实例化它们.

例如:

TaskLayer:在同一名称空间下包含3个类.
A.cs
------

Hi,
I have a project that has 11 classes. Now each class refers to the tasklayer ( another set of multiple classes) and instantiates them everytime.

For ex:

TaskLayer: contains 3 classes under same namespace.
A.cs
------

public class A{}



B.cs
---------



B.cs
---------

public class B{}



C.cs
--------



C.cs
--------

public class C{}




MyProj:我的类需要引用任务层类
_A.cs
------




MyProj: my classes needs to refer to tasklayer classes
_A.cs
------

using Tasklayer;
class _A
{
A a = new A();
B b = new B();
C c = new C();
}



_B.cs
-----



_B.cs
-----

using Tasklayer;
class _B
{
A a = new A();
B b = new B();
C c = new C();
}



_C.cs
------



_C.cs
------

using Tasklayer;
class _C
{
A a = new A();
B b = new B();
C c = new C();
}



现在,我不想为myproj中的每个此类创建单独的对象集.
我想创建单个tasklayer类的对象集,并引用myproj类中的对象.



Now I dont wanna create a separate set of objects for each of these class in myproj.
I want to create a single of set of object of the tasklayer classes and referance those in my myproj classes.

Can you please tell me how to do that.

推荐答案

阿南亚,
公共静态"是解决此问题的方法之一.

Hi ananya,
"public static" is one of the solution for this...

using tasklayer;
namespace MyProj
{
   public static class CommonInstance
   {
      public static A a = new A();
      public static B b = new B();
      public static C c = new C();
   }
   class _A
   {
     //Do here whatever you want to do
     CommonInstance.a.FooFunction(a,a,a);
   }
   class _B
   {
     //Do here whatever you want to do
     CommonInstance.a.FooFunction(b,b,b);
   }
   class _C
   {
      //Do here whatever you want to do
      CommonInstance.a.FooFunction(c,c,c);
   }
}


为什么不尝试创建一个静态助手类,该类将包含一个可以返回您要引用的类实例的方法.
why dont you try creating a static helper class which would contain a method which can return you the instance of the class which you want to refer.


创建一个单例类并使用相同的方法(例如getSingleton())对其进行访问.这应该使您可以访问各种不同类中的同一对象.
Create a singleton class and access it using the same method (say getSingleton()) method. This should give you access to the same object in various different classes.


这篇关于可以在多个类之间共享的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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