string num1 = "12";
string num2 = "13";
int num3;
int num4 = 77;
bool bo;
num3 = int.Parse(Convert.ToString(num2));
bo = int.TryParse(Convert.ToString(num1), out num4);
Console.Write(num3 +","+bo +","+num4 );
int.TryParse(string ,out int ) //把string 字符串转化为int类型。成功返回true,失败返回false. int 型参数成功返回转化过的值,失败返回0。
int.Parse(string ); //把string 参数转化为int值。
1。字符串为空,抛出ArgumentNullException异常。
2.不是数字,抛出FormatException
3.数字超出int 型范围。抛出OverflowException
自定义类型转化。
operator:
public static result-type unary-operator(op-type operand) //一元运算符重载
public static result-type binary-operator(op-type operand ,op-type2 operand2) //二元运算符重载
implicit://隐性转化
public static implicit operator conv-type-out (conv-type-in operand)
explicit://显示转化
public static explict operator conv-type-out(conv-type-in operand)
1.result-type 运算符的结果类型。
2.unary-operator 下列运算符之一:+ - ! ~ ++ — true false
3.op-type 第一个(或唯一一个)参数的类型。
4.operand 第一个(或唯一一个)参数的名称。
5.binary-operator 其中一个:+ - * / % & | ^ << >> == != > < >= <=
6.op-type2 第二个参数的类型。
7.operand2 第二个参数的名称。
8.conv-type-out 类型转换运算符的目标类型。
9.conv-type-in 类型转换运算符的输入类型。
DEMO:
public struct Student
{
private uint yuan;
public uint Yuan
{
get { return yuan; }
set { yuan = value; }
}
private uint jiao;
public uint Jiao
{
get { return jiao; }
set { jiao = value; }
}
private uint fen;
public uint Fen
{
get { return fen; }
set { fen = value; }
}
public Student(uint yuan,uint jiao,uint fen)
{
if (fen > 9)
{
jiao += fen / 10;
fen = fen % 10;
}
if (jiao > 9)
{
yuan += jiao / 10;
jiao = jiao % 10;
}
this.yuan = yuan;
this.jiao = jiao;
this.fen = fen;
}
public override string ToString()
{
return string .Format("${0}元{1}角{2}分",Yuan ,Jiao ,Fen );
}
public static Student operator +( Student s1,Student s2)
{
return new Student(s1.Yuan + s2.Yuan, s1.Jiao + s2.Jiao, s1.Fen + s2.Fen);
}
public static explicit operator float(Student s1)
{
return s1.Yuan +(s1.Jiao /10.0f)+(s1.Fen /100.0f);
}
public static explicit operator Student (float f)
{
uint yuan = (uint)f;//uint 转化性能好,Convert.ToUInt32精度好,但有性能 损失。
uint jiao = (uint)((f - yuan) * 10);
uint fen = Convert.ToUInt32(((f-yuan )*100)%10);
return new Student(yuan,jiao,fen );
}
}
class Program
{
static void Main(string[] args)
{
Student s1, s2,s3,S4;
s1 = new Student(11,11,11);
s2 = new Student(5, 5, 5);
s3 = s1 + s2;
float f = (float )s3;
S4 = (Student )f;
Console.Write(s3 +","+s3.ToString() +","+f +","+S4 );
Console.ReadKey();
}
}