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

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 编程资源 > 编程问答 >内容正文

编程问答

轻松实现深度Clone | Source Generators方式

發(fā)布時(shí)間:2023/12/4 编程问答 36 豆豆
生活随笔 收集整理的這篇文章主要介紹了 轻松实现深度Clone | Source Generators方式 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

前言

在開發(fā)中,我們經(jīng)常需要?jiǎng)?chuàng)建某個(gè)類型實(shí)例的副本。

常用的方式,是繼承ICloneable接口,然后自行實(shí)現(xiàn)Clone(),這會(huì)耗費(fèi)一定的開發(fā)時(shí)間;或者使用序列化/反序列化方式變相實(shí)現(xiàn),但是性能不高。

現(xiàn)在,可以嘗試用Source Generators實(shí)現(xiàn)。

實(shí)現(xiàn)思路

首先,需要Clone的類必須聲明一個(gè)特定的CloneableAttribute,這樣Source Generators才知道為誰(shuí)實(shí)現(xiàn)Clone方法。

然后,Source Generators遍歷該類型的所有屬性,為其編寫屬性賦值代碼。

如果屬性本身也是Cloneable類型,那就調(diào)用屬性對(duì)應(yīng)類型的Clone方法,實(shí)現(xiàn)深度克隆。

具體代碼

1.添加CloneableAttribute

向待編譯項(xiàng)目加入CloneableAttribute代碼:

const?string?cloneableAttributeText?=?@"using?System;namespace?CloneableDemo {public?sealed?class?CloneableAttribute?:?Attribute{public?CloneableAttribute(){}} } ";context.AddSource("CloneableAttribute",?SourceText.From(cloneableAttributeText,?Encoding.UTF8));

2.遍歷CloneableAttribute聲明類

找到聲明了CloneableAttribute的所有類型:

var?cloneableAttribute?=?compilation.GetTypeByMetadataName("CloneableDemo.CloneableAttribute"); foreach?(var?classSymbol?in?classSymbols) {if?(!classSymbol.TryGetAttribute(cloneableAttribute,?out?var?attributes))continue;context.AddSource($"{classSymbol.Name}_clone.cs",?SourceText.From(CreateCloneCode(classSymbol),?Encoding.UTF8)); }

3.生成Clone代碼

遍歷屬性,生成Clone方法:

private?string?CreateCloneableCode(INamedTypeSymbol?classSymbol){string?namespaceName?=?classSymbol.ContainingNamespace.ToDisplayString();var?propertyNames?=?classSymbol.GetMembers().OfType<IPropertySymbol>();var?codes?=?new?StringBuilder();foreach?(var?propertyName?in?propertyNames){if?(isCloneable(propertyName)){codes.AppendLine($@"????????????????{propertyName}?=?obj.{propertyName}?.Clone(),");}else{codes.AppendLine($@"????????????????{propertyName}?=?obj.{propertyName},");}}return?$@"using?System.Collections.Generic;namespace?{namespaceName} {{public?static?class?{classSymbol.Name}Extentions{{public?static?{classSymbol.Name}?Clone(this?{classSymbol.Name}?obj){{return?new?{classSymbol.Name}{{{codes.ToString()}}};}}}} }}";}

4.使用

現(xiàn)在,就可以在目標(biāo)項(xiàng)目中使用Clone方法了:

[Cloneable] public?class?Class1 {public?string?A?{?get;?set;?}public?Class2?B?{?get;?set;?} }[Cloneable] public?class?Class2 {public?string?A?{?get;?set;?} }var?obj?=?new?Class2() {A?=?"My IO", }; var?deep?=?new?Class1() {A?=?"My IO",B?=?obj }; var?clone?=?deep.Clone();

結(jié)論

有了Source Generators,可以讓編譯器幫我們自動(dòng)實(shí)現(xiàn)Clone方法,既節(jié)約了開發(fā)時(shí)間,又保證了性能!

如果你覺得這篇文章對(duì)你有所啟發(fā),請(qǐng)關(guān)注我的個(gè)人公眾號(hào)”My IO“

總結(jié)

以上是生活随笔為你收集整理的轻松实现深度Clone | Source Generators方式的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。