Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 将类型变量作为泛型方法的类型传递_C#_Oop_Generics_Reflection - Fatal编程技术网

C# 将类型变量作为泛型方法的类型传递

C# 将类型变量作为泛型方法的类型传递,c#,oop,generics,reflection,C#,Oop,Generics,Reflection,我有一个字典,它表示值类型枚举和类型域实体之间的关联 Dictionary<SettingType, Type> dictionnary = new Dictionary<SettingType, Type>() { {SettingType.GameBoard, typeof(GameBoardParameterLine)}, {SettingType.Mountain, typeof(MountainPa

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

        Dictionary<SettingType, Type> dictionnary = new Dictionary<SettingType, Type>() {
            {SettingType.GameBoard, typeof(GameBoardParameterLine)},
            {SettingType.Mountain, typeof(MountainParameterLine)},
            {SettingType.Treasure, typeof(TreasureParameterLine)},
            {SettingType.Adventurer, typeof(AdventurerParameterLine)}
        };
Dictionary Dictionary=new Dictionary(){
{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));
    }
公共静态IEnumerable CreateGroupOf(IEnumerable rawDataGroup),其中T:ParameterLine
{
返回rawDataGroup.Select(rawSettings=>(T)Activator.CreateInstance(typeof(T),rawSettings));
}
我想通过传递一个类型为“type”的变量从字典中检索来调用这个静态方法:

            Type currentType = dictionnary.GetValueOrDefault(SettingType.GameBoard);
        IEnumerable<GameBoardParameterLine> parameterLineGroup = ParameterLineGroupFactory.CreateGroupOf<currentType>(data);
Type currentType=dictionnary.GetValueOrDefault(SettingType.GameBoard);
IEnumerable parameterLineGroup=ParameterLineGroupFactory.CreateGroupOf(数据);
问题是我得到了无法隐式转换的异常


我读过这篇文章,但这并不能解决我的问题,因为返回类型是“Object”。

您需要使用反射来调用具有动态类型的CreateGroupOf:

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

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

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