C#抽象类的静态字段继承 [英] C# abstract class static field inheritance
问题描述
我觉得像我跳过一个C#类或两个,但这里是我的困境:
I feel like I skipped a C# class or two, but here's my dilemma:
我有我从中派生多个子类的抽象类。
I have an abstract class from which I derive multiple child classes.
我知道肯定每个子类中,我将有一个需要一定的静态对象作为模型构造这个对象将是每个子类的不同。
I know for sure that for each of the child classes I will have a constructor that needs a certain static object as a model and this object will be different for each of the child classes.
我的第一种方法是使抽象父类中的公共静态对象,然后,我才开始创建子类的任何实例,我将修改为每他们,但事实证明,这种方式实际上我只作一个静态对象,抽象类,以及每个它的子类使用它。
My first approach was to make a public static object in the abstract parent class and then, before I start creating any instances of the child classes, I would modify it for each of them, but it turns out that this way I actually make only ONE static object, for the abstract class, and each of it's child classes uses it.
我怎么能?解决这个问题。
How could I solve the problem?
要更确切地说,这里是伪代码:
To be more exact, here is the pseudocode:
父抽象类:
abstract class AbstractClass
{
static public ModelObject Model;
...
}
一个子类的:
class Child : AbstractClass
{
...
public Child()
{
this.someField = Model.someField;
}
}
编辑:
模型需要是ModelObject类的成员,它不应该是一个单身或其他任何东西。
The Model needs to be a member of the "ModelObject" class, it should NOT be a singleton or anything else.
EDIT2:
要更加准确,我选择一盘棋此实现:我对棋子和子类代表了游戏的混凝土块一个抽象类:走卒,骑士,等等。
To be even more exact, i chose this implementation for a game of chess: I have an abstract class for the chess pieces and the child classes represent the concrete pieces of the game: pawns, knights, et cetera.
抽象类从MeshMatObject,表示与基本功能的通用3D物体,如旋转,网格,材质,纹理等一类继承并将其定义棋局件抽象方法,像GetPossibleMoves()。
The abstract class inherits from MeshMatObject, a class that represents generic 3d objects with the basic functionality, like rotations, meshes, materials, textures and so on and it defines abstract methods for chess game pieces, like GetPossibleMoves().
我上面所讲的模型对象是MeshMatObject的一员,在我看来,应该在类外只有一次定义,然后用于所有的作品。我的意思是:比如所有的棋子具有相同的网格和纹理,所以我不看你想使一个棋子每次给人一种模型参数的点
The Model object I was talking about above is a member of the MeshMatObject and, in my opinion, should be defined outside the class just once and then used for all the pieces. I mean: for example all the pawns have the same mesh and texture, so I don't see the point of giving a model as a parameter every time you want to make a pawn.
推荐答案
我倾向于使用类似@ shf301的解决方案的东西。根据您的需求,它可能有用的设置基类为:
I tend to use something similar to @shf301's solution. Depending on your needs it may useful to setup the base class as:
abstract class AbstractClass
{
}
abstract class AbstractClass<TModel> : AbstractClass
where TModel : ModelObject
{
static public TModel Model;
...
}
这让我一个共同的基类,我可以用在非通用函数工作。这也使派生类型选择确切的型号和可以减少铸造。
This allows me a common base class that I can work with in non-generic functions. This also allows derived types to choose the exact model type and can cut down on casting.
这篇关于C#抽象类的静态字段继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!