3.C#知识点:is和as
生活随笔
收集整理的這篇文章主要介紹了
3.C#知识点:is和as
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
IS和AS 都是用于類型轉換的操作。
但是這兩個有什么區別呢?
簡單的來說 is 判斷成立則返回True,反之返回false。as 成立則返回要轉換的對象,不成立則返回Null。
下面掏一手代碼來說明一下。
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks;namespace IsAndAsTest {class Program{static void Main(string[] args){object child = new Child();bool b1 = (child is Father);bool b2 = (child is Mother);Console.WriteLine(b1);//返回trueConsole.WriteLine(b2);//返回falseConsole.ReadKey();}}public class Father{}public class Child:Father{}public class Mother{} } using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks;namespace IsAndAsTest {class Program{static void Main(string[] args){object child = new Child();//bool b1 = (child is Father);//bool b2 = (child is Mother);//Console.WriteLine(b1);//返回true//Console.WriteLine(b2);//返回false//Console.ReadKey();Father f1 = child as Father;//可以得到轉換成功,得到對象Mother m1 = child as Mother;//轉換失敗,m1的值為null}}public class Father{}public class Child:Father{}public class Mother{} }有一點我要強調一下就是子類可以轉換父類,但是父類不能轉換為子類,這就比如現在這個社會。你父母的東西是你的,但是你的東西還是你的一樣。
?
Father F2 = new Father();Child C1 = (Child)F2;?
第二句代碼轉換的時候就會失敗了。因為父類不能強轉換為子類。Father不能轉換為Child,但是我們如果用As進行轉換的話為得到一個null的c1對象。
總結?
由他們返回值就可以簡單的知道他們的用法。
is 主要用于類型推斷,而不需要實際的轉換。
as 主要用于真正的類型轉換。
?
世上本來沒有路,走的人多了,就是路了。世上也沒有絕對的真理,你成功了,你就是真理。總結
以上是生活随笔為你收集整理的3.C#知识点:is和as的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: chrome 插件开发心得
- 下一篇: FPGA在各行业的应用分析