Is it possible to save a Type (using “typeof()”) in an enum?

前端 未结 7 1067
旧巷少年郎
旧巷少年郎 2021-01-30 10:32

So I\'m creating a game in XNA, C# 4.0, and I need to manage a lot of PowerUps (which in code are all inherited from class \"PowerUp\"), and to handle back-end management of the

7条回答
  •  一整个雨季
    2021-01-30 11:04

    You can't do it as the value of an enum, but you could specify it in an attribute:

    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
    }
    

    You can then extract those attribute values at execution time with reflection. However, I would personally just create a dictionary:

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

    No need for a special attribute, no need to extract the values with fiddly reflection code.

提交回复
热议问题