C# 中的 is 和 as 运算符 简单举例说明
假設有一個接口:IBankAccount;一個類SaverAccount,類SaverAccout繼承自IBankAccount接口,如下圖所示:
public interface IBankAccount {public interface IBankAccount{void PayIn(decimal amount);bool Withdraw(decimal amount);decimal Balance{get;}} }public class SaverAccount : IBankAccount {private decimal _balance;public void PayIn(decimal amount) => _balance += amount;public bool Withdraw(decimal amount){if(_balance >= amount){_balance -= amount;return true;}WriteLine("Withdrawl attempt failed");return false;}public decimal Balance => _balance;public override string ToString() => $"Venus Bank Saver:Balance ={_balance,6:C}"$ }正是因為繼承關系,SaverAccount可以直接分配給IBankAccount接口,如下圖所示:
IBankAccount venusAccount = new SaverAccount();如果一個方法接受一個對象類型,現在希望訪問IBankAccount成員,該怎么辦呢?該對象類型沒有IBankAccount接口成員。此時可以進行類型轉換,把對象(也可以使用任何接口中的任意類型的參數,把它裝化為需要的類型)轉化為IBankAccount,再處理它:
public void WorkWithManyDifferentObjects(object o) {IBankAccount account = (IBankAccount)o;//work with the account }只要總是給這個方法提供一個IBankAccount類型的對象,這就是有效的。當然,如果接受一個object類型的對象,有時就換傳遞無效的對象。此時會得到InvalidCastException 異常。在正常情況下接受異常從來都不好。此時應該使用 is 和 as 運算符。
不是直接進行類型的轉化,而應該檢查參數是否實現了接口IBankAccount。as 運算符的工作原理類似于層次結構中的 cast運算符——它返回對象的引用。然而,它從不拋出InvalidCastException異常,如果這個對象不是所要求的類型,這個運算符就返回null。
public void WorkWithManyDifferentObjects(object o) {IBankAccount account = o as IBankAccount;if( account != null){//work with the account} }?除了使用as運算符之外,還可以使用is運算符。 is運算符根據條件是否滿足,對象是否使用指定的類型,返回true或者false.驗證條件是true后,可以進行類型轉換,因為現在,類型轉換總會成功。
public void WorkWithManyDifferentObjects(object o) {if(o is IBankAccount){IBankAccount account = (IBankAccount)o;//work with the account} }?在類層次結構內部的類型轉換,不會拋出基于類型轉換的異常,而且使用is 和 as 運算符都是可以的。
?
?
?
總結
以上是生活随笔為你收集整理的C# 中的 is 和 as 运算符 简单举例说明的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C#中IEnumerableT.Grou
- 下一篇: C#中IEnumerableT.Join