定义"自定义"整数型为主? [英] Define "custom" integer-based type?

查看:121
本文介绍了定义"自定义"整数型为主?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个是与,除其他事项外,有装在一个大结构的无符号12位值的外部库接口程序。

I have a program that is interfacing with an external library that, among other things, has an unsigned 12-bit value packed in a larger struct.

这使用为8位,所以我们干脆封它为一个字节。

This used to be 8 bits, so we simply marshaled it as a byte.

现在,它是12位...我可以用一个USHORT,但它开创了问题(一)检查的范围和(b)封送处理。

Now that it's 12 bits... I can use a ushort, but that opens up issues of (a) range checking and (b) marshaling.

有没有实施约束的数字类型像这样的一个简单的方法,在这里我没有覆盖所有的分配和?比较法

Is there a simple way of implementing a constrained numeric type like this, where I don't have to override every assignment and comparison method?

推荐答案

您应该创建一个覆盖隐式转换操作符的结构:

You should create a struct that overrides the implicit conversion operator:

struct PackedValue
{
    private PackedValue(ushort val)
    {
         if(val >= (1<<12)) throw new ArgumentException();
         this._value = val;
    }
    private ushort _value;
    public static explicit operator PackedValue(ushort value){
        return new PackedValue(value);
    }

    public static implicit operator ushort(PackedValue me){
        return me._value;
    }
}

这篇关于定义&QUOT;自定义&QUOT;整数型为主?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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