2015-01-23 2 views
0

다음과 같은 문제가 있습니다. 정수 값 또는 부동 소수점 값을 바이트 배열로 변환하고 싶습니다. 일반적으로 BitConverter.GetBytes() 메서드를 사용합니다.C# 암시 적/명시 적 바이트 배열 변환

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

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

암시 적/명시 적 방법으로이 작업을 수행 할 가능성이 있습니까 ??

arr = i; 
arr = a; 

그리고 다른 방법으로 ??

i = arr; 
a = arr; 
+4

아니요. –

답변

4

중급 클래스를 통해 수행 할 수 있습니다. 컴파일러는 두 개의 암시 적 캐스트를 단독으로 수행하지 않으므로 하나의 명시 적 형변환을 수행해야합니다. 그러면 컴파일러에서 두 번째 캐스팅을 찾습니다.

문제는 암시 적 캐스트와 함께, 당신은 당신이 캐스트를 선언 유형에서 또는 캐스트 중 하나를해야한다는 것입니다, 당신은 '내부'와 같은 밀폐 된 클래스에서 상속 할 수 없습니다.

이렇게 우아하지 않습니다. 확장 메서드는 아마 더 우아합니다. 아래의 클래스를 선언하면

, 당신은 다음과 같은 일을 할 수 있습니다

 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}; 
    } 
} 
3
당신은 조금 호출 코드를 정리하는 확장 메서드를 만들 수

- 그래서 당신은 좋겠 와 끝까지 :

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

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

확장 방법에 대한 코드는 것 같은 뭔가 :

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); 
     } 
    }