简体   繁体   English

静态类存储为属性

[英]Static class stored as a property

I have a static abstract class called State , it defines the abstract methods start() and update() , and then I have multiple classes which implement State . 我有一个称为State的静态抽象类,它定义了抽象方法start()update() ,然后有多个实现State的类。

Now I want to create a class, let's call it StateMachine , that has a property called currentState . 现在,我想创建一个类,让我们称之为StateMachine ,它具有一个名为currentState的属性。 I want to be able to set this property pointing to a static class implementing state so I can run things like currentState.update() . 我希望能够将此属性设置为指向实现状态的静态类,以便可以运行currentState.update()之类的东西。

Now comes my question: 现在是我的问题:

What should be the type of the property? 物业的类型应该是什么? I'd say State but I feel like there's something more to it. 我会说国家,但我觉得还有更多的东西。 Also, how would I go into setting the property? 另外,我将如何设置属性? is

currentState = ClassThatImplementsState;

a valid thing to do? 一个有效的事情吗?

EDIT: Ok, so I just learned that you cannot inherit from a static class in C#. 编辑:好的,所以我才知道您不能从C#中的静态类继承。 I'd like to know a way of doing something similar to this that would allow me both the polymorfism and not having to instantiate the state objects. 我想知道一种做类似的事情的方法,这种方法可以使我既有多态性,又不必实例化状态对象。 Is there such a thing? 有这样的事吗?

If State is a static class, you can't have multiple classes that "implement", ie derive from it. 如果State静态类,则不能有多个“实现”(即从其派生)的类。 When, on the other hand, it is an abstract class, you can derive from it. 另一方面,当它是抽象类时,可以从中派生。 But it can't be both. 但这不可能两者兼而有之。

EDIT: I think what you actually want is a Singleton rather than an abstract or static class. 编辑:我认为您真正想要的是Singleton,而不是抽象或静态类。 See http://msdn.microsoft.com/en-us/library/ff650316.aspx for hints how to implenent the Singleton pattern in C#. 有关如何在C#中实现Singleton模式的提示,请参见http://msdn.microsoft.com/zh-cn/library/ff650316.aspx

EDIT 2: If your application is multithreaded, be sure to use a thread safe variant of the Singleton pattern. 编辑2:如果您的应用程序是多线程的,请确保使用单例模式的线程安全变体。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM