C# non-boxing conversion of generic enum to int?

前端 未结 9 1951
庸人自扰
庸人自扰 2020-12-04 07:31

Given a generic parameter TEnum which always will be an enum type, is there any way to cast from TEnum to int without boxing/unboxing?

See this example code. This w

9条回答
  •  南笙
    南笙 (楼主)
    2020-12-04 07:46

    If you'd like to speed up conversion, restricted to use unsafe code and can't emit IL you may want to consider to make generic class as abstract and implement conversion in derived classes. For example, when you code for Unity engine you probably want to build IL2CPP targets which are not compatible with emit. Here is an example of how it can be implemented:

    // Generic scene resolver is abstract and requires
    // to implement enum to index conversion
    public abstract class SceneResolver : ScriptableObject
        where TSceneTypeEnum : Enum
    {
        protected ScenePicker[] Scenes;
    
        public string GetScenePath ( TSceneTypeEnum sceneType )
        {
            return Scenes[SceneTypeToIndex( sceneType )].Path;
        }
    
        protected abstract int SceneTypeToIndex ( TSceneTypeEnum sceneType );
    }
    
    // Here is some enum for non-generic class
    public enum SceneType
    {
    }
    
    // Some non-generic implementation
    public class SceneResolver : SceneResolver
    {
        protected override int SceneTypeToIndex ( SceneType sceneType )
        {
            return ( int )sceneType;
        }
    }
    
    

    I tested boxing vs. virtual method and got 10x speed up for virtual method approach on macOS for both Mono and IL2CPP targets.

提交回复
热议问题