类型转换

 

隐式转换:

namespace wpf
{   class oppo
    {

    }

    class Coppo : oppo //类Coppo是类oppo的子类
    {

    }
    class Program
    {
        static void Main(string[] args)
        {
            int inum = 100;
            long lnum = inum; // 进行了隐式转换,将 int 型(数据范围小)数据转换为了 long 型(数据范围大)的数据
            oppo c1 = new Coppo(); // 这里也是隐式转换,将一个新建的 Coppo 实例转换为了其基类 oppo类型的实例 C1
        }
    }
}

显式转换

double dnum = 100.1;
int ifromd = (int)dnum; //double类型显式转换转为int类型

oppo c11 = new oppo();
Coppo c22 = c11 as Coppo; //使用as进行显式转换
Console.WriteLine(c22 is oppo);
Console.WriteLine(c22 is Coppo);
 

类型之间的转换 - Convert 和 Parse

string locstr = 123.ToString();

//如果要将"locstr"转成整型数

//方法一: 用 Convert 
int i = Convert.ToInt16(locstr);

//方法二: 用 Parse
int ii = int.Parse(locstr);


另外:
int.TryParse(string s,out int i)

该方式也是将数字内容的字符串转换为int类型,但是该方式比int.Parse(string s) 好一些,它不会出现异常,最后一个参数result是输出值,如果转换成功则输出相应的值,转换失败则输出0。

class test
{
    static void Main(string[] args)
    {
        string s1="abcd";
        string s2="1234";
        int a,b;
        bool bo1=int.TryParse(s1,out a);
        Console.WriteLine(s1+" "+bo1+" "+a);
        bool bo2=int.TryParse(s2,out b);
        Console.WriteLine(s2+" "+bo2+" "+b);
    }
}

 



posted @ 2017-11-13 18:29  赤那王鹏飞  阅读(41)  评论(0)    收藏  举报