mercredi 22 avril 2020

Passing Type variable as a type of generic method [duplicate]

I have a dictionnary that represent a association between a value type enum and a type domain entity.

        Dictionary<SettingType, Type> dictionnary = new Dictionary<SettingType, Type>() {
            {SettingType.GameBoard, typeof(GameBoardParameterLine)},
            {SettingType.Mountain, typeof(MountainParameterLine)},
            {SettingType.Treasure, typeof(TreasureParameterLine)},
            {SettingType.Adventurer, typeof(AdventurerParameterLine)}
        };

I have this following generic method that works fine:

        public static IEnumerable<T> CreateGroupOf<T>(IEnumerable<IEnumerable<string>> rawDataGroup) where T : ParameterLine
    {
        return rawDataGroup.Select(rawSettings => (T)Activator.CreateInstance(typeof(T), rawSettings));
    }

I want to call this static method by passing a variable of type "Type" retrieve from dictionnary :

            Type currentType = dictionnary.GetValueOrDefault(SettingType.GameBoard);
        IEnumerable<GameBoardParameterLine> parameterLineGroup = ParameterLineGroupFactory.CreateGroupOf<currentType>(data);

The problem is that i got cannot implicity convert exception.

I read this Using System.Type to call a generic method but that doesn't resolve a problem for me beacause of the return type that is "Object".





Aucun commentaire:

Enregistrer un commentaire