简体   繁体   English

C#隐式/显式字节数组转换

[英]C# Implicit/Explicit Byte Array Conversion

I have following problem. 我有以下问题。 I want to convert an integer value or float value into an byte array. 我想将整数值或浮点值转换为字节数组。 Normaly I use the BitConverter.GetBytes() method. 通常,我使用BitConverter.GetBytes()方法。

int i = 10;
float a = 34.5F;
byte[] arr;

arr = BitConverter.GetBytes(i);
arr = BitConverter.GetBytes(a);

Is there a possibility to do this with implicit/explicit methods?? 是否有可能使用隐式/显式方法执行此操作?

arr = i;
arr = a;

and also the other way around?? 还有另一种方式吗?

i = arr;
a = arr;

You can do it through an intermediate class. 您可以通过中间类来实现。 The compiler won't do two implicit casts by itself, so you must do one explicit cast and then the compiler will figure out the second one. 编译器本身不会执行两个隐式强制转换,因此您必须执行一个显式强制转换,然后编译器将找出第二个隐式强制转换。

The problem is that with implicit casts, you must either cast to or from the type you declare the cast in, and you cannot inherit from sealed classes like 'int'. 问题是,与隐式类型转换,则必须强制转换 声明中投的类型,你无法从密封类像“诠释”继承。

So, it is not elegant at all. 因此,它一点也不优雅。 Extension methods are probably more elegant. 扩展方法可能更优雅。

If you declare the class below, you can then do things like: 如果在下面声明该类,则可以执行以下操作:

        byte[] y = (Qwerty)3;
        int x = (Qwerty) y;

public class Qwerty
{
    private int _x;

    public static implicit operator byte[](Qwerty rhs)
    {
        return BitConverter.GetBytes(rhs._x);
    }

    public static implicit operator int(Qwerty rhs)
    {
        return rhs._x;
    }

    public static implicit operator Qwerty(byte[] rhs)
    {
        return new Qwerty {_x = BitConverter.ToInt32(rhs, 0)};
    }

    public static implicit operator Qwerty(int rhs)
    {
        return new Qwerty {_x = rhs};
    }
}

you could create extension methods to clean up the calling code a little bit - so you'd end up with: 您可以创建扩展方法来稍微清理调用代码-因此最终得到:

 int i = 10;
 float a = 34.5F;
 byte[] arr;

 arr = i.ToByteArray();
 arr = a.ToByteArray();

The code for the extension methods would be something like: 扩展方法的代码如下:

public static class ExtensionMethods
    {
        public static byte[] ToByteArray(this int i)
        {
            return BitConverter.GetBytes(i);
        }

        public static byte[] ToByteArray(this float a)
        {
            return BitConverter.GetBytes(a);
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM