当前位置: 移动技术网 > IT编程>开发语言>c# > C#之IP地址和整数互转的小例子

C#之IP地址和整数互转的小例子

2019年07月18日  | 移动技术网IT编程  | 我要评论
源码:复制代码 代码如下:[structlayout(layoutkind.explicit)] public struct ip { &nb

源码:

复制代码 代码如下:

[structlayout(layoutkind.explicit)]
 public struct ip
 {
     public ip(uint32 value)
     {
         this._text1 = 0;
         this._text2 = 0;
         this._text3 = 0;
         this._text4 = 0;
         this._value = value;
     }
     public ip(byte text1, byte text2, byte text3, byte text4)
     {
         this._value = 0;
         this._text1 = text1;
         this._text2 = text2;
         this._text3 = text3;
         this._text4 = text4;
     }
     [fieldoffset(0)]
     private uint32 _value;
     [fieldoffset(0)]
     private byte _text1;
     [fieldoffset(1)]
     private byte _text2;
     [fieldoffset(2)]
     private byte _text3;
     [fieldoffset(3)]
     private byte _text4;

     public uint32 value
     {
         get { return this._value; }
         set { this._value = value; }
     }
     public byte text1
     {
         get { return this._text1; }
         set { this._text1 = value; }
     }
     public byte text2
     {
         get { return this._text2; }
         set { this._text2 = value; }
     }
     public byte text3
     {
         get { return this._text3; }
         set { this._text3 = value; }
     }
     public byte text4
     {
         get { return this._text4; }
         set { this._text4 = value; }
     }

     public override string tostring()
     {
         return string.format("{0}.{1}.{2}.{3}", this._text1.tostring(), this._text2.tostring(),
             this._text3.tostring(), this._text4.tostring());
     }

     public static implicit operator ip(uint32 value)
     {
         return new ip(value);
     }
     public static explicit operator uint32(ip ip)
     {
         return ip._value;
     }
 }

测试:

复制代码 代码如下:

class program
 {
     static void main(string[] args)
     {
         ip ip = new ip(192,168,1,1);
         console.writeline(ip);
         uint32 value = (uint32)ip;
         console.writeline(value);
         console.writeline(ip.value);
         ip ip2 = (ip)(1234567);
         console.writeline(ip2);

         console.readkey();
     }
 }

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网