将原始类型转换为泛型类型? [英] Convert primitive to generic type?

查看:41
本文介绍了将原始类型转换为泛型类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在解析二进制文件.因此,我写了一些类似于以下内容:

I'm parsing binary files. As such I have written something akin to the following:

public T Parse<T>(BinaryReader reader)
{
    if (typeof(T) == typeof(byte))
        return reader.ReadByte();
    else if (typeof(T) == typeof(int))
        return reader.ReadInt32();
    // ...
}

但是这不会编译:

无法将类型 '...' 隐式转换为 'T'

Cannot implicitly convert type '...' to 'T'

这样做对我来说会很方便.

It would be very convenient for me to do this.

如何从泛型方法返回任何原语?

How do I return any primitive from a generic method?

推荐答案

这在检查运行时类型的通用代码中很常见.您必须向上转换为对象,然后向下转换为泛型 T.这是因为编译器不知道"字节可以直接转换为 T,即使它与 T 相同,因为类型检查.

This is fairly common with generic code that checks runtime types. You have to upcast to object then downcast to the generic T. This is because the compiler doesn't 'know' the byte is directly convertible to T even it is identical to T because of the type check.

public T Parse<T>(BinaryReader reader)
{
    if (typeof(T) == typeof(byte))
        return (T)(object)reader.ReadByte();
    else if (typeof(T) == typeof(int))
        return (T)(object)reader.ReadInt32();
    // all returns will need similar casts
}

这样做的缺点是转换为对象会导致装箱操作并增加 GC 压力,因此可能对性能敏感的代码不利.

The downside to this is that the cast to object causes a boxing operation and adds to GC pressure so it could be bad for performance sensitive code.

这篇关于将原始类型转换为泛型类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆