关于C# as类型转换

首次发布:2017-06-04 12:01
using System;

namespace 类型转换
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                Student s1 = new Student();
                Person p = new Person();
                //Student s2 = (Student)p;//这样父类转子类,虽然不报错,但运行时会出错
                Student s = p as Student;//这样转,如果成功则有返回值,如果失败则返回空
                //Person p1 = (Person)s1;//这样转可以转,但建设用下面的转换,效力高
                Person p2 = s1 as Person;
                Console.Write(s+"============"+p2);
            }
            catch (Exception ex)
            {

            }
            
            Console.ReadKey();
        }
    }
    public class Person
    {
        string s = "123";
    }
    public class Student : Person
    {
        string S2 = "ABC";
    }
}