日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > C# >内容正文

C#

3.C#知识点:is和as

發布時間:2025/4/5 C# 26 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。