c# - 通用 TypeCode 类型检查?

标签 c# generics

我应该避免使用泛型进行类型检查吗?不使用传统的类型检查比较(myvar is int),而是使用类型的类型代码。

使用泛型,通过类型检查,您可以创建一个不带参数的方法来支持常规重载方法的任务。这是无参数方法的问题,它们不能被重载。

// "Buffer" is the byte[] while "Peek" is the read/write position. Then Align" is the alignment size in bytes of the buffer.
public type Read<type>() {
    switch( Type.GetTypeCode( typeof( type ) ) ) {
        case System.TypeCode.Boolean:
            bool bool_val = ( Buff[ Peek ] > 0 );
            Peek = ( ++Peek + ( Align - 1 ) ) & ~( Align - 1 );
            return (type)(object)bool_val;
        case System.TypeCode.Byte:
            byte byte_val = Buff[ Peek ];
            Peek = ( ++Peek + ( Align - 1 ) ) & ~( Align - 1 );
            return (type)(object)byte_val;
        case TypeCode.Ushort:
            ushort ushort_val = (ushort)( Buff[ Peek ] | ( Buff[ Peek + 1 ] << 8 ) );
            Peek += 2;
            Peek = ( Peek + ( Align - 1 ) ) & ~( Align - 1 );
            return (type)(object)ushort_val;
        break;
        ...
    }
}

这似乎是实现无参数方法重载形式的唯一方法。这被认为是不好的做法吗?

最佳答案

你可以用这样的东西使你的代码通用:

var size = Marshal.SizeOf(typeof(T));
var subBuffer = new byte[size];
Array.Copy(Buff, Peek, subBuffer, 0, size);
var handle = GCHandle.Alloc(subBuffer, GCHandleType.Pinned);
var ptr = handle.ToIntPtr();
var val = (T)Marshal.PtrToStructure(ptr, typeof(T));
ptr.Free();
Peek += size;
Peek = ( Peek + ( Align - 1 ) ) & ~( Align - 1 );
return val;

但是,如果您的用例遇到性能问题,那么提供硬编码的专用版本可能不是一个坏方法,因为没有任何明显的替代方案。

关于c# - 通用 TypeCode 类型检查?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30834446/

相关文章:

C#抽象类说明

c# - 将 Python 标准输入/输出重定向到 C# 表单应用程序

generics - 如何确保泛型中的类型实现 Dart 中的某些运算符?

c# - 从 'V'到 'System.IEquatable<V>'没有装箱转换或者类型参数转换

java - Java 泛型的问题

c# - 如何自定义一个asp :Button class?

c# - 我在 ASP.net core MVC 和 Azure iot hub 中遇到错误

c# - 覆盖 linq 属性 c#

c# - 使用泛型调用重载方法

c# - 带表格的通用 CSV 导出