首页 > 解决方案 > 如何传递类型思维方法并返回不同的列表类型

问题描述

好的,所以这有点超出我的想象。另外,我什至不知道是否可以这样做

我真的不知道很多这个的条款

首先,这是为太空工程师准备的一款我玩的游戏,它有开放的 c# 脚本来与游戏交互,我发现它非常有趣,也是学习一些代码基础知识的好方法

现在我要做的是创建一个方法,我认为这就是所谓的“内部列表<> GetBlocksWithName”,这个方法的作用是搜索船上的所有块,然后将其转换为正确的类型然后返回该类型的列表

但我的问题是我想最后传递我想转换的“类型”。不仅当我尝试调用该方法时,它会告诉我它无效。当我尝试将方法中传递的类型用作类型时,它说它不是类型

另外,如果每次都是不同的类型,我不确定如何将列表发回

这是我正在使用的代码

    internal void BlockScan()
    {
        GetBlocksWithName(IMyMotorAdvancedStator, "SolarHing"); // <- compile error IMyMotorAdvancedStator ('IMyMotorAdvancedStator' is a type, witch is not vaild in the give context)
        return;
    }
    internal List<> GetBlocksWithName(Type blockType,string nameOfBlocks) // <- compile error List<>(Unexpected use of an unbound generic name) its because of an unfinshed return not sure how to specife the type if it will be different every time
    {
        List<IMyTerminalBlock> temp = new List<IMyTerminalBlock>();
        GridTerminalSystem.SearchBlocksOfName(nameOfBlocks, temp);
        return temp.ConvertAll(x => (blockType)x); // <- compile error blockType ('blockType' is a varible but is used like a type)
    }

我知道里面有很多专门针对太空工程师脚本的东西,但是如果有人可以帮助我,我会非常有帮助,在此先感谢

标签: c#

解决方案


Try the following

internal void BlockScan()
{
    GetBlocksWithName<IMyMotorAdvancedStator>("SolarHing"); 
    return;
}

internal List<T> GetBlocksWithName<T>(string nameOfBlocks) 
{
    List<IMyTerminalBlock> temp = new List<IMyTerminalBlock>();
    GridTerminalSystem.SearchBlocksOfName(nameOfBlocks, temp);
    return temp.ConvertAll(x => (T)x); 
}

You pass in the Type = T as a generic, and use the Generic T to convert your variable x to the correct type.

Have a look at Generic programming in the documentation. To get a better understanding.


推荐阅读