c# - 是否可以在枚举中保存类型(使用 "typeof()")?

标签 c# types enums type-conversion

所以我在 XNA、C# 4.0 中创建一个游戏,我需要管理很多 PowerUps(在代码中都是从类“PowerUp”继承的),并处理 PowerUps 的后端管理我当前有一个枚举 PowerupEffectType,每个子类 PowerUp 都有一个值。最后,在代码中,我需要将 PowerupEffectType 转换为 Powerup 类型(属于 Type 类,通常使用 typeof([class name]) 实现)。

因为这是一个小组项目,我想尽可能地将 PowerupEffectType 的每个值与其对应的类 Type 结合起来,即:不只是期望我的其他程序员使用 switch 语句手动进行转换,并确保添加/expansions 后来涉及尽可能少的地方尽可能少的变化。我有几个选择,到目前为止我发现的最好的方法是创建枚举伪方法,将所有内容压缩到一个 switch 语句(我想要的 99%),这要归功于我在这里找到的一些提示:http://msdn.microsoft.com/en-us/library/bb383974.aspx

但我想更进一步 - 我可以在 enum 中保存一个 Type 吗? 我知道你可以保存枚举作为特定类型(链接:http://msdn.microsoft.com/en-us/library/cc138362.aspx),但 Type 不是其中之一。当前的选择是 byte、sbyte、short、ushort、int、uint、long 和 ulong。是否有任何可行的方法来保存将 Type 转换为上述任何数据类型并返回?

澄清一下,这是我希望我能做的,我正在寻找一种方法:

// (Assuming 'LightningPowerup', 'FirePowerup', and 'WaterPowerup' are
// all declared classes that inherit from a single base class)

public enum PowerupEffectType
{
    LIGHTNING = typeof(LightningPowerup),
    FIRE = typeof(FirePowerup),
    WATER = typeof(WaterPowerup)
}

有什么办法可以做到这一点,还是我只是将已经完成 99% 的问题的解决方案过于复杂化了?

提前致谢!

最佳答案

您不能将其作为枚举的,但您可以在属性中指定它:

using System;
using System.Runtime.CompilerServices;

[AttributeUsage(AttributeTargets.Field)]
public class EffectTypeAttribute : Attribute
{
    public Type Type { get; private set; }

    public EffectTypeAttribute(Type type)
    {
        this.Type = type;
    }
}

public class LightningPowerup {}
public class FirePowerup {}
public class WaterPowerup {}

public enum PowerupEffectType
{
    [EffectType(typeof(LightningPowerup))]
    Lightning,
    [EffectType(typeof(FirePowerup))]
    Fire,
    [EffectType(typeof(WaterPowerup))]
    Water
}

然后您可以在执行时使用反射提取这些属性值。但是,我个人只是创建一个字典:

private static Dictionary<PowerupEffectType, Type> EffectTypeMapping =
    new Dictionary<PowerupEffectType, Type>
{
    { PowerupEffectType.Lightning, typeof(LightningPowerup) },
    { PowerupEffectType.Fire, typeof(FirePowerup) },
    { PowerupEffectType.Water, typeof(WaterPowerup) }
};

不需要特殊的属性,不需要用繁琐的反射代码提取值。

关于c# - 是否可以在枚举中保存类型(使用 "typeof()")?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11008853/

相关文章:

mysql - 我们怎么能不允许 mysql 中的枚举不为空?

C# float 转十进制

c# - 从 Linq GroupBy 中检索值

haskell - 这个 Haskell 函数的类型签名是什么?

linq - Entity Framework 、每种类型的表和 Linq - 获取 "Type"

c++ - C 和 C++ 中 char 的区别?

c - 在 C 中访问 union 体成员的成员

c# Wpf 将枚举绑定(bind)到组合框

c# - Enum.Parse 抛出 InvalidCastException

c# - 如何伪造数据 GridView 片段的可见性?