轻松实现深度Clone | Source Generators方式
前言
在開發(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)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 如何提升 Kestrel 上传文件的大小
- 下一篇: 初探IdentityServer4(客户