1、使用 as 而不要用 is

public class ShouldAsNotIs
    {
        public void ShouldAs()
        {
            object a = new ShouldAsNotIs();
            var b = a as ShouldAsNotIs;
            if (b == null)
            {
                b.Show();
            }
        }

        public void NotIs()
        {
            object a = new ShouldAsNotIs();
            if (a is ShouldAsNotIs)
            {
                var b = a as ShouldAsNotIs;
                //or
                b = (ShouldAsNotIs)a;
                b.Show();
            }
        }
        public string Show()
        {
            return @"ShouldAs 强转了一次,NotIs 强转了两次,强转应当尽量避免,
转换为接口》转换为实体类 
转换为子类》转换 为父类
";
        }
    }

 

posted @ 2019-06-24 19:53  zwsu  阅读(215)  评论(0编辑  收藏  举报