gpt4 book ai didi

c# - 有没有办法在 C# 的子类中强制存在静态成员?

转载 作者:太空狗 更新时间:2023-10-29 23:11:01 30 4
gpt4 key购买 nike

对于基于图 block 的游戏,我使用不同的类来描述不同图 block 类型的行为。它们(显然)派生自基类。现在我有一个问题,有时我需要弄清楚玩家是否有足够的资金来支付升级到某种瓷砖类型的费用。

由于瓷砖类型的成本始终保持不变,因此将其设为静态似乎是有意义的。不幸的是,C# 似乎不允许使用抽象类或接口(interface)来强制在子类中存在此类静态字段。

我的“解决方案”是使用反射来获取这些数据,但在我看来这相当丑陋并且有潜在危险,因为我可能会忘记其中一个子类中的静态字段,这会破坏整个事情......

以下代码片段是我目前拥有的; AllowedUpdatesList<System.Type>包含磁贴可以升级到的类型。

foreach (Type t in AllowedUpdates) {

// Get the Action Point Cost
FieldInfo fi = t.GetField ("actionPointCost", BindingFlags.NonPublic | BindingFlags.Static);
int cost = (int)fi.GetValue (null);

// Check for any requirements
bool requirementsFulfilled;
try {
// Get the static method that checks the necessary requirements.
MethodInfo mi = t.GetMethod ("CheckRequirements", new Type[] { typeof(Dictionary<string, ProtoObject>) });
object[] arguments = { neighbourFields };

// Invoke this method
object returnValue = mi.Invoke (null, arguments);
requirementsFulfilled = (bool)returnValue;
} catch (ArgumentNullException) {
// This type has no special requirements, pass it.
requirementsFulfilled = true;
} catch (NullReferenceException) {
// No requirements needed, pass it.
requirementsFulfilled = true;
}
}

必须有更好的方法来做到这一点。是否有我忽略的设计模式?

最佳答案

您不能通过抽象基类或接口(interface)强制在任何派生类上存在 static 成员。

反射不是你最好的选择。在这种情况下重新考虑您对 static 类的使用。您可以将 tile 类型的成本设为 abstract 只读属性。派生类将被迫实现该属性。

public abstract int ActionPointCost { get; }

关于c# - 有没有办法在 C# 的子类中强制存在静态成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4509554/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com