【发布时间】:2020-05-26 21:01:24
【问题描述】:
我正在解析二进制文件。因此,我写了类似于以下内容的内容:
public T Parse<T>(BinaryReader reader)
{
if (typeof(T) == typeof(byte))
return reader.ReadByte();
else if (typeof(T) == typeof(int))
return reader.ReadInt32();
// ...
}
但是这不能编译:
无法将类型“...”隐式转换为“T”
这样做对我来说很方便。
如何从泛型方法返回任何原语?
【问题讨论】:
-
"但是这不能编译。"意味着您遇到了编译错误。这是什么?
-
你必须像
return (byte)(object)reader.ReadByte()一样投射,但这让我想知道调用者通过调用Parse<byte>(reader)而不是read.ReadByte()得到了什么。您将对该方法返回的任何值类型进行装箱。 -
@ZoharPeled 添加了错误。
-
-
@Cobra_Fast 哦,对不起。我的意思是
return (T)(object)reader.ReadByte()。
标签: c# .net-core type-conversion