加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 06:00:43 所属栏目:百科 来源:网络整理
导读:源码: 复制代码 代码如下: [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 text

源码:

复制代码 代码如下:

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读