浅析 record 使用场景
淺析 record 使用場(chǎng)景
Intro
之前我們有介紹過(guò) record 基本知識(shí),可以參考?C# 9 新特性 — record 解讀,record 會(huì)實(shí)現(xiàn)基于值的類(lèi)型比較,最近遇到的幾個(gè)問(wèn)題覺(jué)得用 record 來(lái)解決會(huì)非常方便,分享一下
基于值的類(lèi)型比較
最近有遇到一個(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é)果不同,于是我就想寫(xiě)一段代碼調(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ì)重寫(xiě) Equals 方法還會(huì)重寫(xiě) 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)類(lèi)型的對(duì)象,不再需要自己做強(qiáng)制類(lèi)型轉(zhuǎn)換了,上面的做法還是比較取巧的辦法,使用了 MemberwiseClone 去做復(fù)制,如果自己寫(xiě)代碼一個(gè)一個(gè)復(fù)制,將會(huì)更加繁瑣,使用 record 之后就很簡(jiǎn)單了,只是我們需要注意一下,with 表達(dá)式也只是淺復(fù)制,如果內(nèi)部包含復(fù)雜引用類(lèi)型,需要小心使用
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;} }More
record 在很多場(chǎng)景下能夠簡(jiǎn)化我們的代碼,使得代碼更加干凈簡(jiǎn)潔,在合適的場(chǎng)景下不要忘記使用哦~
微軟的反向代理項(xiàng)目 YARP 也使用了 record 來(lái)簡(jiǎn)化原來(lái)代碼中 DeepClone 的功能,可以參考 PR:https://github.com/microsoft/reverse-proxy/pull/662
總結(jié)
以上是生活随笔為你收集整理的浅析 record 使用场景的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: C# ObservableCollect
- 下一篇: 后宫佳丽三千,假如古代皇帝也懂负载均衡算