Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/three.js/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 具有对象的全局静态类_C#_Oop_Static - Fatal编程技术网

C# 具有对象的全局静态类

C# 具有对象的全局静态类,c#,oop,static,C#,Oop,Static,好的,我知道静态类中不能有对象,但是我需要一个类,我可以保存可以从不同类访问的对象。我正在制作一个dll,它将为另一个程序提供扩展功能,所以我不能仅仅继承或传递类。如果需要的话,我可以把我需要的每个对象的属性放在静态类中,这样可以工作,但不像我希望的那样友好。有人对如何完成这样的事情有其他想法吗 实际上,静态类中可以有对象——它们必须是静态对象 例如: public static class SharedObjects { private static MyClass obj = new

好的,我知道静态类中不能有对象,但是我需要一个类,我可以保存可以从不同类访问的对象。我正在制作一个dll,它将为另一个程序提供扩展功能,所以我不能仅仅继承或传递类。如果需要的话,我可以把我需要的每个对象的属性放在静态类中,这样可以工作,但不像我希望的那样友好。有人对如何完成这样的事情有其他想法吗

实际上,静态类中可以有对象——它们必须是静态对象

例如:

public static class SharedObjects
{
    private static MyClass obj = new MyClass();
    public static MyClass GetObj() 
    {
        return obj;
    }
}
您可以从程序的其他地方调用实例方法/属性等:

SharedObjects.GetObj().MyInstanceMethod();

一种选择是让一个类具有访问静态对象的访问器方法。系统的其他部分可以将该类用作静态类或非静态类。代码如下:

  public class GlobalInformation {
     public static GlobalInformation CreateInstance() {
        // Factory method through GlobalInformmation.CreateInstance()
        return new GlobalInformation();
     }

     public GlobalInformation() {
        // Regular use through new GlobalInformation()
     }

     static GlobalInformation() {
        // Static initializer called once before class is used.
        // e.g. initialize values:
        _aString = "The string value";
     }

     public string AccessAString {
        get {
           return _aString;
        }
     }

     public Foo AccessAnObject() {
        return _anObject;
     }

     private static string _aString;
     private static readonly Foo _anObject = new Foo();
  }
系统的其他部分将使用它,如下所示。备选案文1:

var globalInfo = GlobalInformation.CreateInstance();
var aString = globalInfo.AssessAString;
var anObj = globalInfo.AccessAnObject();
备选案文2:

var globalInfo = new GlobalInformation();
var aString = globalInfo.AssessAString;
var anObj = globalInfo.AccessAnObject();

选项2是我的首选方法(我会删除静态工厂方法
CreateInstance()
),因为您可以随时更改实现,包括使(某些)字段成为非静态字段。在共享数据时,它将显示为一个常规类。

您考虑过依赖注入和/或托管扩展性框架吗?您第一句话说OK的原因是什么?它实际上被命名为Singleton模式。我确实尝试过这个,但我得到了这个错误,这就是为什么我想到这里的原因:这就是为什么我认为静态类中不能有对象错误1可访问性不一致:返回类型“MyNameSpace.MyClass”的可访问性不如方法“MyNameSpace.StaticClass.GetObj()”在这种情况下,请检查MyClass的访问修饰符。它需要是公共的,而不是私有的或内部的。@cf正如曼弗雷德所说,请确保
MyClass
声明为
public-class-MyClass
。@Justin:Yes。类必须是公共的,才能从不同的程序集访问。在嵌套类的情况下,它需要是公共的,即使在从同一程序集中使用时也是如此。是的,这就是我忘记将对象类设置为公共的问题。谢谢大家。