c# - 如何传递类型思维方法并返回不同的列表类型
问题描述
好的,所以这有点超出我的想象。另外,我什至不知道是否可以这样做
我真的不知道很多这个的条款
首先,这是为太空工程师准备的一款我玩的游戏,它有开放的 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)
}
我知道里面有很多专门针对太空工程师脚本的东西,但是如果有人可以帮助我,我会非常有帮助,在此先感谢
解决方案
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.
推荐阅读
- sonarqube - java.lang.RuntimeException:无法以 root 身份运行 elasticsearch
- javascript - 在实现我们自己的调用方法时,是否需要检查 typeof this == 'function' ?
- c# - Xamarin.Forms ScrollView 降低了它在 ios 上的高度
- mysql - SQL:组合两个查询结果,它们有一个共同的列,但每个都有自己特定的唯一列
- c++ - 使用 Docker 开发环境通过 Qt Creator 调试 Qt 应用程序
- python - 在 Python 中按照 Networkx 上的特定顺序绘制节点?
- python - 如何使用 httplib 刷新 HTTPConnection
- c# - 如果在启动期间失败,ASP.NET 显示“站点关闭”页面而不是 YSOD
- angular - ng2 搜索管道一列过滤器
- javascript - 如何使用 Vue 发出本地存储更改?