【问题标题】:Passing Type variable as a type of generic method [duplicate]将类型变量作为泛型方法的类型传递[重复]
【发布时间】:2020-04-22 10:24:07
【问题描述】:

我有一个字典,表示值类型枚举和类型域实体之间的关联。

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

我有以下通用方法可以正常工作:

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

我想通过传递从字典中检索的“类型”类型的变量来调用这个静态方法:

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

问题是我不能隐式转换异常。

我读到了这个Using System.Type to call a generic method,但这并不能解决我的问题,因为返回类型是“Object”。

【问题讨论】:

  • 谢谢,但不起作用,因为返回类型是 Object,我需要一个类型化的返回类型。
  • Convert.ChangeType

标签: c# oop generics reflection


【解决方案1】:

你需要使用反射来调用动态类型的CreateGroupOf:

IEnumerable parameterLineGroup = 
   typeof(ParameterLineGroupFactory)
   .GetMethod("CreateGroupOf")
   .MakeGenericMethod(currentType)
   .Invoke(null, new object[] { data }) as IEnumerable;

虽然 parameterLineGroup 是无类型可枚举的,因为 currentType 可能不是 GameBoardParameterLine。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-27
    • 1970-01-01
    • 1970-01-01
    • 2022-06-11
    相关资源
    最近更新 更多