C#之IP地址和整数互转的小例子
程序员文章站
2023-12-03 09:02:40
源码:复制代码 代码如下:[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();
}
}
上一篇: Vue render函数实战之实现tabs选项卡组件
下一篇: 详解Vue依赖收集引发的问题
推荐阅读