溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

c#中record的使用場(chǎng)景有哪些

發(fā)布時(shí)間:2021-02-03 16:10:45 來(lái)源:億速云 閱讀:203 作者:Leah 欄目:開發(fā)技術(shù)

今天就跟大家聊聊有關(guān)c#中record的使用場(chǎng)景有哪些,可能很多人都不太了解,為了讓大家更加了解,小編給大家總結(jié)了以下內(nèi)容,希望大家根據(jù)這篇文章可以有所收獲。

基于值的類型比較

最近有遇到一個(gè)場(chǎng)景,需要比較兩個(gè) JSON 字符串是否相等,字符串比較簡(jiǎn)單,就是一個(gè)固定值的 Dictionary,或者認(rèn)為它就是一個(gè)簡(jiǎn)單的 Model,但是 JSON 字符串的的屬性順序可能不同,比如說(shuō)下面的這個(gè)示例:

{"Id":1, "Name":"Tom"}, {"Name":"Tom", "Id":1},這兩個(gè)字符串從字符串上來(lái)說(shuō)順序不同,自然不相等,但是對(duì)應(yīng)的屬性的值是相同的,怎么比較方便的進(jìn)行比較呢,使用 record 可以比較方便進(jìn)行比較,來(lái)看代碼:

record Person(int Id, string Name);

[Fact]
public void RecordTest()
{
 var str1 = "{\"Id\":1, \"Name\":\"Tom\"}";
 var p1 = JsonConvert.DeserializeObject<Person>(str1);

 var str2 = "{\"Name\":\"Tom\",\"Id\":1}";
 var p2 = JsonConvert.DeserializeObject<Person>(str2);

 Assert.True(p1 == p2);
 Assert.Equal(p1, p2);
}

基于值比較的去重

我們有一個(gè) API 有收到反饋說(shuō),調(diào)用多次返回的結(jié)果不同,于是我就想寫一段代碼調(diào)用個(gè)一百次看是否會(huì)有重復(fù),大致代碼如下:

public record Result
{
 public string Data { get; set;}
 public int Code { get; set; }
}

var i = 100;
var results = new HashSet<Result>();
using var httpClient = new HttpClient();
while(i-- > 0)
{
 var responseText = await httpClient.GetStringAsync("");
 var result = JsonConvert.DeserializeObject<Result>(responseText);
 results.Add(result);
}
Console.WriteLine(results.Count);

因?yàn)?record 不僅會(huì)重寫 Equals 方法還會(huì)重寫 GetHashCode 方法,所以可以使用 HashSet 或者 Dictionary 來(lái)實(shí)現(xiàn)去重

對(duì)象克隆

record 提供了 with 表達(dá)式來(lái)方便的克隆一個(gè)新的對(duì)象,所以在需要克隆的時(shí)候可以考慮使用 record,另外所有原型模式的地方都可以考慮使用 record 來(lái)實(shí)現(xiàn)

之前我實(shí)現(xiàn)了一個(gè)簡(jiǎn)單的日志框架,有一個(gè)日志對(duì)象,定義如下:

public class LogHelperLoggingEvent : ICloneable
{
 public string CategoryName { get; set; }

 public DateTimeOffset DateTime { get; set; }

 public string MessageTemplate { get; set; }

 public string Message { get; set; }

 public LogHelperLogLevel LogLevel { get; set; }

 public Dictionary<string, object> Properties { get; set; }

 public LogHelperLoggingEvent Copy() 
 {
 var newEvent = new LogHelperLoggingEvent()
 {
  CategoryName = CategoryName,
  DateTime = DateTime,
  MessageTemplate = MessageTemplate,
  Message = Message,
  LogLevel = LogLevel
 };
 if (Properties != null)
 {
  newEvent.Properties = new Dictionary<string, object>();
  foreach (var property in Properties)
  {
  newEvent.Properties[property.Key] = property.Value;
  }
 }
 return newEvent;
 }
}

我們可以使用 MemberwiseClone 做一個(gè)簡(jiǎn)化

public class LogHelperLoggingEvent : ICloneable
{
 public string CategoryName { get; set; }

 public DateTimeOffset DateTime { get; set; }

 public string MessageTemplate { get; set; }

 public string Message { get; set; }

 public LogHelperLogLevel LogLevel { get; set; }

 public Dictionary<string, object> Properties { get; set; }

 public LogHelperLoggingEvent Copy()
 {
 var newEvent = (LogHelperLoggingEvent)MemberwiseClone();
 if (Properties != null)
 {
  newEvent.Properties = new Dictionary<string, object>();
  foreach (var property in Properties)
  {
  newEvent.Properties[property.Key] = property.Value;
  }
 }
 return newEvent;
 }
}

使用了 record 之后如下,with 表達(dá)式返回的是強(qiáng)類型的對(duì)象,不再需要自己做強(qiáng)制類型轉(zhuǎn)換了,上面的做法還是比較取巧的辦法,使用了 MemberwiseClone 去做復(fù)制,如果自己寫代碼一個(gè)一個(gè)復(fù)制,將會(huì)更加繁瑣,使用 record 之后就很簡(jiǎn)單了,只是我們需要注意一下,with 表達(dá)式也只是淺復(fù)制,如果內(nèi)部包含復(fù)雜引用類型,需要小心使用

public record LogHelperLoggingEvent
{
 public string CategoryName { get; set; }

 public DateTimeOffset DateTime { get; set; }

 public string MessageTemplate { get; set; }

 public string Message { get; set; }

 public LogHelperLogLevel LogLevel { get; set; }

 public Dictionary<string, object> Properties { get; set; }

 public LogHelperLoggingEvent Copy()
 {
 var newEvent = this with{ };
 if (Properties != null)
 {
  newEvent.Properties = new Dictionary<string, object>();
  foreach (var property in Properties)
  {
  newEvent.Properties[property.Key] = property.Value;
  }
 }
 return newEvent;
 }
}

看完上述內(nèi)容,你們對(duì)c#中record的使用場(chǎng)景有哪些有進(jìn)一步的了解嗎?如果還想了解更多知識(shí)或者相關(guān)內(nèi)容,請(qǐng)關(guān)注億速云行業(yè)資訊頻道,感謝大家的支持。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI