使用类类型创建接口列表,然后强制转换为类型返回 null
本文关键字:类型 转换 返回 然后 null 创建 接口 列表 | 更新日期: 2023-09-27 18:35:56
尝试在一个简单的解析器项目中制作一个通用的加载文件来列出函数。只要我使用 IList<接口>它就会返回一个列表,但是当尝试转换为实际的 List<类时>它返回 null。类时>接口>
public async static Task<IList<IFileHandlerLineVO>> LoadLineByLine(string path, Type toClass)
{
if (!FileExist(path))
return null;
List<IFileHandlerLineVO> list = new List<IFileHandlerLineVO>();
StreamReader fs = new StreamReader(path);
string readline;
while ((readline = await fs.ReadLineAsync()) != null)
{
IFileHandlerLineVO instance = (IFileHandlerLineVO)Activator.CreateInstance(toClass);
instance.Input = readline;
list.Add(instance);
// NOTE: A cast here shows that instance is the correct class 'GameSortVO'
}
fs.Close();
fs.Dispose();
return list;
}
具有接口的类(值对象)
public class GameSortVO : IFileHandlerLineVO
{
public string Input { get; set; }
public string Output { get; set; }
public int Number { get; set; }
public int Random { get; set; }
}
这就是我使用它的方式。这行得通
IList<IFileHandlerLineVO> list = await FileHandler.LoadLineByLine(game.Filepath, typeof(GameSortVO)) as IList<IFileHandlerLineVO>;
但是,我想运行这个。没有任何建议?
IList<GameSortVO> list = await FileHandler.LoadLineByLine(game.Filepath, typeof(GameSortVO)) as IList<GameSortVO>;
breakpoint shows
list null System.Collections.Generic.IList<parser.vo.GameSortVO>
您需要强制转换元素,而不是列表本身。可以使用 Linq 的 Cast 方法来强制转换元素:
var list = await LoadLineByLine("aaa", typeof(GameSortVO));
var listGameSortVO = list.Cast<GameSortVO>();