小编xeo*_*hin的帖子

是否可以在C#中使用{a,b,c}实例化队列?

是否有可能在C#中做到这一点?

Queue<string> helperStrings = {"right", "left", "up", "down"};
Run Code Online (Sandbox Code Playgroud)

或者我必须首先制作阵列?

c# arrays queue icollection

5
推荐指数
2
解决办法
1747
查看次数

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

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

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

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

以下代码片段是我目前拥有的代码片段; 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 …
Run Code Online (Sandbox Code Playgroud)

c# reflection static

5
推荐指数
1
解决办法
295
查看次数

标签 统计

c# ×2

arrays ×1

icollection ×1

queue ×1

reflection ×1

static ×1