如何在 C# 中使用隐式和显式操作符
C# 有一個鮮為人知的特性是通過定義 顯式和隱式操作符 實現類型之間的轉換,這篇文章我們將會討論如何使用這些 顯式 和 隱式 操作符。
什么是顯式,什么是隱式
隱式類型轉換 它是運行時自動幫你完成的,言外之意就是你不需要人為干預,比如下面的例子就是典型的 隱式類型轉換。
int?x?=?100;? double?d?=?x;不過下面的代碼則過不了編譯器。
double?d?=?100.25; int?x?=?d;編譯程序時,將會出現下面的錯誤。
顯而易見,上面的 double 不能隱式的轉成 int,除非顯式轉換,那如何顯式呢?可以使用如下代碼。
int?x?=?100;? double?d?=?(int)?x;人工干預后,編譯器也就放行了。
創建 DTO 類
接下來我們研究一下如何在 用戶自定義類型 上使用 隱式 和 顯式轉換,比如:Class,考慮下面的類。
public?class?Author{public?Guid?Id?{?get;?set;?}public?string?FirstName?{?get;?set;?}public?string?LastName?{?get;?set;?}}public?class?AuthorDto{public?string?Id?{?get;?set;?}public?string?FirstName?{?get;?set;?}public?string?LastName?{?get;?set;?}}在上面的代碼中,定義了一個 Author 實體類,然后再為 Author 定義一個數據傳輸對象 AuthorDTO,數據傳輸對象是一個數據容器,常用于在 Presentation 和 Application層 之間傳遞數據。
Model 和 DTO 之間的相互轉換
下面的代碼展示了如何實現 Author 和 AuthorDto 之間的相互轉換。
public?AuthorDto?ConvertAuthorToAuthorDto(Author?author){AuthorDto?authorDto?=?new?AuthorDto{Id?=?author.Id.ToString(),FirstName?=?author.FirstName,LastName?=?author.LastName};return?authorDto;}public?Author?ConvertAuthorDtoToAuthor(AuthorDto?authorDto){Author?author?=?new?Author{Id?=?Guid.Parse(authorDto.Id),FirstName?=?authorDto.FirstName,LastName?=?authorDto.LastName};return?author;}如果需要在應用程序中為若干個類寫這樣的轉換代碼,你會發現實現類之間的轉換使的代碼比較冗余,而且代碼可讀性也好不到哪里去。所以在這種場景下就是 顯式 和 隱式 操作符的用武之地。
使用隱式操作符
實現 model-dto 之間的轉換更簡單粗暴的方式就是使用 隱顯式操作符,這樣就避免了冗長的方法調用,讓代碼更加的直截了當。
下面的代碼展示了如何使用 隱式操作符 將 Author實例 轉成 AuthorDto 實例。
public?static?implicit?operator?AuthorDto(Author?author) {AuthorDto?authorDto?=?new?AuthorDto();authorDto.Id?=?author.Id.ToString();authorDto.FirstName?=?author.FirstName;authorDto.LastName?=?author.LastName;return?authorDto; }接下來看一下如何在 Main 方法中使用 隱式操作符。
static?void?Main(string[]?args) {Author?author?=?new?Author();author.Id?=?Guid.NewGuid();author.FirstName?=?"Joydip";author.LastName?=?"Kanjilal";AuthorDto?authorDto?=?author;Console.ReadKey(); }使用顯式操作符
下面的代碼展示了如何利用 顯式操作符 將 Author 實例轉成 AuthorDto 。
public?static?explicit?operator?AuthorDto(Author?author) {AuthorDto?authorDto?=?new?AuthorDto();authorDto.Id?=?author.Id.ToString();authorDto.FirstName?=?author.FirstName;authorDto.LastName?=?author.LastName;return?authorDto; }這時候在 Main 方法中就需要人工介入進行強轉了,如下代碼所示:
static?void?Main(string[]?args) {Author?author?=?new?Author();author.Id?=?Guid.NewGuid();author.FirstName?=?"Joydip";author.LastName?=?"Kanjilal";AuthorDto?authorDto?=?(AuthorDto)author;Console.ReadKey(); }值得注意的是,你不能在一個類中的對象轉換同時定義 顯式 和 隱式操作符,如下圖所示:
如果你定義了隱式操作符,那么對象之間的轉換可以是隱式或顯式,如果你定義了顯式操作符,那么你只能顯式的實現對象轉換,雖然隱式操作使用起來非常方便,但顯式操作會讓代碼意圖更明顯,可讀性更高。
譯文鏈接:https://www.infoworld.com/article/3606436/how-to-use-implicit-and-explicit-operators-in-csharp.html
總結
以上是生活随笔為你收集整理的如何在 C# 中使用隐式和显式操作符的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: BeetleX.Http.Clients
- 下一篇: 杨中科.NET5视频教程更新了:DI、配