轻松实现深度Clone | Source Generators方式
生活随笔
收集整理的這篇文章主要介紹了
轻松实现深度Clone | Source Generators方式
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
前言
在開發(fā)中,我們經常需要創(chuàng)建某個類型實例的副本。
常用的方式,是繼承ICloneable接口,然后自行實現Clone(),這會耗費一定的開發(fā)時間;或者使用序列化/反序列化方式變相實現,但是性能不高。
現在,可以嘗試用Source Generators實現。
實現思路
首先,需要Clone的類必須聲明一個特定的CloneableAttribute,這樣Source Generators才知道為誰實現Clone方法。
然后,Source Generators遍歷該類型的所有屬性,為其編寫屬性賦值代碼。
如果屬性本身也是Cloneable類型,那就調用屬性對應類型的Clone方法,實現深度克隆。
具體代碼
1.添加CloneableAttribute
向待編譯項目加入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.使用
現在,就可以在目標項目中使用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();結論
有了Source Generators,可以讓編譯器幫我們自動實現Clone方法,既節(jié)約了開發(fā)時間,又保證了性能!
如果你覺得這篇文章對你有所啟發(fā),請關注我的個人公眾號”My IO“
總結
以上是生活随笔為你收集整理的轻松实现深度Clone | Source Generators方式的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 如何提升 Kestrel 上传文件的大小
- 下一篇: 2022年终结版WPF项目实战合集发布