C#之IP地址和整數互轉的小例子

來源:互聯網
上載者:User

源碼:

複製代碼 代碼如下:[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();
}
}

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.