├── .gitignore ├── AutoCopy.sln ├── AutoCopyLib ├── Attributes │ ├── CopyIgnoreAttribute.cs │ ├── CopyMapAttribute.cs │ └── CopyRequiredAttribute.cs ├── AutoCopy.cs ├── AutoCopyLib.csproj ├── DefaultPropertyExpressionProvider.cs ├── DelegateDecompiler.dll ├── FastExpressionCompiler.cs ├── FindProperty.cs ├── LockingConcurrentDictionary.cs ├── Mono.Reflection.dll ├── OldExpressionVisitor.cs ├── Option.cs ├── ParameterTuple.cs ├── Properties │ └── AssemblyInfo.cs ├── ReflectExt.cs ├── Reorganization.cs ├── TargetExpressionProviderBase.cs ├── TypeConverter.cs ├── TypeTuple.cs ├── Utilities │ ├── Guard.cs │ ├── StaticReflection.cs │ └── VariableGenerator.cs └── Visitors │ ├── ConditionFalseRewriter.cs │ ├── FunctionCompositionExtensions.cs │ ├── GetTryBodyRewriter.cs │ ├── NullsafeQueryRewriter.cs │ └── ReturnTargetRewriter.cs ├── Console.Test ├── App.config ├── Clock.cs ├── Console.Test.csproj ├── Program.cs ├── Properties │ └── AssemblyInfo.cs └── packages.config ├── DataRowTest ├── App.config ├── DataRowExpressionProvider.cs ├── DataRowTest.csproj ├── Program.cs ├── Properties │ └── AssemblyInfo.cs ├── SimpleModel.cs └── packages.config ├── LICENSE ├── README.md ├── README_CN.md └── Web.Test ├── App_Code ├── AutoCopyUtils.cs ├── Data.cs └── HttpRequestParamsExpressionProvider.cs ├── Global.asax ├── Handler.ashx ├── Web.Debug.config ├── Web.config └── packages.config /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.suo 8 | *.user 9 | *.userosscache 10 | *.sln.docstates 11 | 12 | # User-specific files (MonoDevelop/Xamarin Studio) 13 | *.userprefs 14 | 15 | # Build results 16 | [Dd]ebug/ 17 | [Dd]ebugPublic/ 18 | [Rr]elease/ 19 | [Rr]eleases/ 20 | x64/ 21 | x86/ 22 | bld/ 23 | [Bb]in/ 24 | [Oo]bj/ 25 | [Ll]og/ 26 | 27 | # Visual Studio 2015 cache/options directory 28 | .vs/ 29 | # Uncomment if you have tasks that create the project's static files in wwwroot 30 | #wwwroot/ 31 | 32 | # MSTest test Results 33 | [Tt]est[Rr]esult*/ 34 | [Bb]uild[Ll]og.* 35 | 36 | # NUNIT 37 | *.VisualState.xml 38 | TestResult.xml 39 | 40 | # Build Results of an ATL Project 41 | [Dd]ebugPS/ 42 | [Rr]eleasePS/ 43 | dlldata.c 44 | 45 | # .NET Core 46 | project.lock.json 47 | project.fragment.lock.json 48 | artifacts/ 49 | **/Properties/launchSettings.json 50 | 51 | *_i.c 52 | *_p.c 53 | *_i.h 54 | *.ilk 55 | *.meta 56 | *.obj 57 | *.pch 58 | *.pdb 59 | *.pgc 60 | *.pgd 61 | *.rsp 62 | *.sbr 63 | *.tlb 64 | *.tli 65 | *.tlh 66 | *.tmp 67 | *.tmp_proj 68 | *.log 69 | *.vspscc 70 | *.vssscc 71 | .builds 72 | *.pidb 73 | *.svclog 74 | *.scc 75 | 76 | # Chutzpah Test files 77 | _Chutzpah* 78 | 79 | # Visual C++ cache files 80 | ipch/ 81 | *.aps 82 | *.ncb 83 | *.opendb 84 | *.opensdf 85 | *.sdf 86 | *.cachefile 87 | *.VC.db 88 | *.VC.VC.opendb 89 | 90 | # Visual Studio profiler 91 | *.psess 92 | *.vsp 93 | *.vspx 94 | *.sap 95 | 96 | # TFS 2012 Local Workspace 97 | $tf/ 98 | 99 | # Guidance Automation Toolkit 100 | *.gpState 101 | 102 | # ReSharper is a .NET coding add-in 103 | _ReSharper*/ 104 | *.[Rr]e[Ss]harper 105 | *.DotSettings.user 106 | 107 | # JustCode is a .NET coding add-in 108 | .JustCode 109 | 110 | # TeamCity is a build add-in 111 | _TeamCity* 112 | 113 | # DotCover is a Code Coverage Tool 114 | *.dotCover 115 | 116 | # Visual Studio code coverage results 117 | *.coverage 118 | *.coveragexml 119 | 120 | # NCrunch 121 | _NCrunch_* 122 | .*crunch*.local.xml 123 | nCrunchTemp_* 124 | 125 | # MightyMoose 126 | *.mm.* 127 | AutoTest.Net/ 128 | 129 | # Web workbench (sass) 130 | .sass-cache/ 131 | 132 | # Installshield output folder 133 | [Ee]xpress/ 134 | 135 | # DocProject is a documentation generator add-in 136 | DocProject/buildhelp/ 137 | DocProject/Help/*.HxT 138 | DocProject/Help/*.HxC 139 | DocProject/Help/*.hhc 140 | DocProject/Help/*.hhk 141 | DocProject/Help/*.hhp 142 | DocProject/Help/Html2 143 | DocProject/Help/html 144 | 145 | # Click-Once directory 146 | publish/ 147 | 148 | # Publish Web Output 149 | *.[Pp]ublish.xml 150 | *.azurePubxml 151 | # TODO: Comment the next line if you want to checkin your web deploy settings 152 | # but database connection strings (with potential passwords) will be unencrypted 153 | *.pubxml 154 | *.publishproj 155 | 156 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 157 | # checkin your Azure Web App publish settings, but sensitive information contained 158 | # in these scripts will be unencrypted 159 | PublishScripts/ 160 | 161 | # NuGet Packages 162 | *.nupkg 163 | # The packages folder can be ignored because of Package Restore 164 | **/packages/* 165 | # except build/, which is used as an MSBuild target. 166 | !**/packages/build/ 167 | # Uncomment if necessary however generally it will be regenerated when needed 168 | #!**/packages/repositories.config 169 | # NuGet v3's project.json files produces more ignorable files 170 | *.nuget.props 171 | *.nuget.targets 172 | 173 | # Microsoft Azure Build Output 174 | csx/ 175 | *.build.csdef 176 | 177 | # Microsoft Azure Emulator 178 | ecf/ 179 | rcf/ 180 | 181 | # Windows Store app package directories and files 182 | AppPackages/ 183 | BundleArtifacts/ 184 | Package.StoreAssociation.xml 185 | _pkginfo.txt 186 | 187 | # Visual Studio cache files 188 | # files ending in .cache can be ignored 189 | *.[Cc]ache 190 | # but keep track of directories ending in .cache 191 | !*.[Cc]ache/ 192 | 193 | # Others 194 | ClientBin/ 195 | ~$* 196 | *~ 197 | *.dbmdl 198 | *.dbproj.schemaview 199 | *.jfm 200 | *.pfx 201 | *.publishsettings 202 | orleans.codegen.cs 203 | 204 | # Since there are multiple workflows, uncomment next line to ignore bower_components 205 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 206 | #bower_components/ 207 | 208 | # RIA/Silverlight projects 209 | Generated_Code/ 210 | 211 | # Backup & report files from converting an old project file 212 | # to a newer Visual Studio version. Backup files are not needed, 213 | # because we have git ;-) 214 | _UpgradeReport_Files/ 215 | Backup*/ 216 | UpgradeLog*.XML 217 | UpgradeLog*.htm 218 | 219 | # SQL Server files 220 | *.mdf 221 | *.ldf 222 | *.ndf 223 | 224 | # Business Intelligence projects 225 | *.rdl.data 226 | *.bim.layout 227 | *.bim_*.settings 228 | 229 | # Microsoft Fakes 230 | FakesAssemblies/ 231 | 232 | # GhostDoc plugin setting file 233 | *.GhostDoc.xml 234 | 235 | # Node.js Tools for Visual Studio 236 | .ntvs_analysis.dat 237 | node_modules/ 238 | 239 | # Typescript v1 declaration files 240 | typings/ 241 | 242 | # Visual Studio 6 build log 243 | *.plg 244 | 245 | # Visual Studio 6 workspace options file 246 | *.opt 247 | 248 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 249 | *.vbw 250 | 251 | # Visual Studio LightSwitch build output 252 | **/*.HTMLClient/GeneratedArtifacts 253 | **/*.DesktopClient/GeneratedArtifacts 254 | **/*.DesktopClient/ModelManifest.xml 255 | **/*.Server/GeneratedArtifacts 256 | **/*.Server/ModelManifest.xml 257 | _Pvt_Extensions 258 | 259 | # Paket dependency manager 260 | .paket/paket.exe 261 | paket-files/ 262 | 263 | # FAKE - F# Make 264 | .fake/ 265 | 266 | # JetBrains Rider 267 | .idea/ 268 | *.sln.iml 269 | 270 | # CodeRush 271 | .cr/ 272 | 273 | # Python Tools for Visual Studio (PTVS) 274 | __pycache__/ 275 | *.pyc 276 | 277 | # Cake - Uncomment if you are using it 278 | # tools/** 279 | # !tools/packages.config 280 | 281 | # Telerik's JustMock configuration file 282 | *.jmconfig 283 | 284 | # BizTalk build output 285 | *.btp.cs 286 | *.btm.cs 287 | *.odx.cs 288 | *.xsd.cs 289 | -------------------------------------------------------------------------------- /AutoCopy.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 14 4 | VisualStudioVersion = 14.0.25420.1 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Console.Test", "Console.Test\Console.Test.csproj", "{619CDDB5-2283-499C-BEFB-7B32C10FAEA7}" 7 | EndProject 8 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AutoCopyLib", "AutoCopyLib\AutoCopyLib.csproj", "{C2685DAB-9618-4FDC-8E85-248E1069AC39}" 9 | EndProject 10 | Project("{E24C65DC-7377-472B-9ABA-BC803B73C61A}") = "Web.Test", "Web.Test\", "{501CD4B3-6BF8-48E8-86EB-D0517BEA2E3C}" 11 | ProjectSection(SvnOrigin) = preProject 12 | @Keys = Enlist,Svn.Uri 13 | Enlist = Required 14 | Svn.Uri = Web.Test/ 15 | EndProjectSection 16 | ProjectSection(WebsiteProperties) = preProject 17 | SccProjectName = "Svn" 18 | SccAuxPath = "Svn" 19 | SccLocalPath = "Svn" 20 | SccProvider = "SubversionScc" 21 | TargetFrameworkMoniker = ".NETFramework,Version%3Dv4.5" 22 | ProjectReferences = "{c2685dab-9618-4fdc-8e85-248e1069ac39}|AutoCopyLib.dll;" 23 | Debug.AspNetCompiler.VirtualPath = "/localhost_63606" 24 | Debug.AspNetCompiler.PhysicalPath = "Web.Test\" 25 | Debug.AspNetCompiler.TargetPath = "PrecompiledWeb\localhost_63606\" 26 | Debug.AspNetCompiler.Updateable = "true" 27 | Debug.AspNetCompiler.ForceOverwrite = "true" 28 | Debug.AspNetCompiler.FixedNames = "false" 29 | Debug.AspNetCompiler.Debug = "True" 30 | Release.AspNetCompiler.VirtualPath = "/localhost_63606" 31 | Release.AspNetCompiler.PhysicalPath = "Web.Test\" 32 | Release.AspNetCompiler.TargetPath = "PrecompiledWeb\localhost_63606\" 33 | Release.AspNetCompiler.Updateable = "true" 34 | Release.AspNetCompiler.ForceOverwrite = "true" 35 | Release.AspNetCompiler.FixedNames = "false" 36 | Release.AspNetCompiler.Debug = "False" 37 | VWDPort = "63606" 38 | SlnRelativePath = "Web.Test\" 39 | DefaultWebSiteLanguage = "Visual C#" 40 | EndProjectSection 41 | EndProject 42 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DataRowTest", "DataRowTest\DataRowTest.csproj", "{FB83AFCB-3523-47D7-B849-A9032294EC46}" 43 | EndProject 44 | Global 45 | GlobalSection(SubversionScc) = preSolution 46 | Svn-Managed = True 47 | Manager = AnkhSVN - Subversion Support for Visual Studio 48 | EndGlobalSection 49 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 50 | Debug|Any CPU = Debug|Any CPU 51 | Release|Any CPU = Release|Any CPU 52 | EndGlobalSection 53 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 54 | {619CDDB5-2283-499C-BEFB-7B32C10FAEA7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 55 | {619CDDB5-2283-499C-BEFB-7B32C10FAEA7}.Debug|Any CPU.Build.0 = Debug|Any CPU 56 | {619CDDB5-2283-499C-BEFB-7B32C10FAEA7}.Release|Any CPU.ActiveCfg = Release|Any CPU 57 | {619CDDB5-2283-499C-BEFB-7B32C10FAEA7}.Release|Any CPU.Build.0 = Release|Any CPU 58 | {C2685DAB-9618-4FDC-8E85-248E1069AC39}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 59 | {C2685DAB-9618-4FDC-8E85-248E1069AC39}.Debug|Any CPU.Build.0 = Debug|Any CPU 60 | {C2685DAB-9618-4FDC-8E85-248E1069AC39}.Release|Any CPU.ActiveCfg = Release|Any CPU 61 | {C2685DAB-9618-4FDC-8E85-248E1069AC39}.Release|Any CPU.Build.0 = Release|Any CPU 62 | {501CD4B3-6BF8-48E8-86EB-D0517BEA2E3C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 63 | {501CD4B3-6BF8-48E8-86EB-D0517BEA2E3C}.Debug|Any CPU.Build.0 = Debug|Any CPU 64 | {501CD4B3-6BF8-48E8-86EB-D0517BEA2E3C}.Release|Any CPU.ActiveCfg = Debug|Any CPU 65 | {501CD4B3-6BF8-48E8-86EB-D0517BEA2E3C}.Release|Any CPU.Build.0 = Debug|Any CPU 66 | {FB83AFCB-3523-47D7-B849-A9032294EC46}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 67 | {FB83AFCB-3523-47D7-B849-A9032294EC46}.Debug|Any CPU.Build.0 = Debug|Any CPU 68 | {FB83AFCB-3523-47D7-B849-A9032294EC46}.Release|Any CPU.ActiveCfg = Release|Any CPU 69 | {FB83AFCB-3523-47D7-B849-A9032294EC46}.Release|Any CPU.Build.0 = Release|Any CPU 70 | EndGlobalSection 71 | GlobalSection(SolutionProperties) = preSolution 72 | HideSolutionNode = FALSE 73 | EndGlobalSection 74 | EndGlobal 75 | -------------------------------------------------------------------------------- /AutoCopyLib/Attributes/CopyIgnoreAttribute.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace AutoCopyLib.Attributes 4 | { 5 | [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)] 6 | public class CopyIgnoreAttribute : Attribute 7 | { 8 | 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /AutoCopyLib/Attributes/CopyMapAttribute.cs: -------------------------------------------------------------------------------- 1 | using AutoCopyLib.Utilities; 2 | using System; 3 | 4 | namespace AutoCopyLib.Attributes 5 | { 6 | [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)] 7 | public class CopyMapAttribute : Attribute 8 | { 9 | private string _mapName; 10 | public CopyMapAttribute(string mapName) 11 | { 12 | Guard.ArgumentNotNullOrEmpty(mapName, mapName); 13 | _mapName = mapName; 14 | } 15 | public string MapName 16 | { 17 | get 18 | { 19 | return _mapName; 20 | } 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /AutoCopyLib/Attributes/CopyRequiredAttribute.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace AutoCopyLib.Attributes 4 | { 5 | [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)] 6 | public class CopyRequiredAttribute:Attribute 7 | { 8 | private string errMsgFormat; 9 | public CopyRequiredAttribute(string errMsg=null) 10 | { 11 | if (string.IsNullOrEmpty(errMsg)) 12 | errMsgFormat = "not found {0}"; 13 | else 14 | errMsgFormat = errMsg; 15 | } 16 | public string MsgFormat 17 | { 18 | get 19 | { 20 | return errMsgFormat; 21 | } 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /AutoCopyLib/AutoCopy.cs: -------------------------------------------------------------------------------- 1 | using AutoCopyLib.Attributes; 2 | using AutoCopyLib.Utilities; 3 | using AutoCopyLib.Visitors; 4 | using DelegateDecompiler; 5 | using System; 6 | using System.Collections.Generic; 7 | using System.Linq; 8 | using System.Linq.Expressions; 9 | using System.Reflection; 10 | using System.Reflection.Emit; 11 | 12 | namespace AutoCopyLib 13 | { 14 | public class AutoCopy 15 | { 16 | public static AutoCopy CreateMap() 17 | { 18 | return new AutoCopy(); 19 | } 20 | } 21 | public partial class AutoCopy 22 | { 23 | private static ConstantExpression ReturnTrue = Expression.Constant(true, typeof(bool)); 24 | private static ConstantExpression ReturnFalse = Expression.Constant(false, typeof(bool)); 25 | delegate bool RefFunc(ref TDest dest, TSource src, out string errMsg); 26 | internal AutoCopy() 27 | { 28 | var p1 = Expression.Parameter(typeof(TDest).MakeByRefType(), "dest"); 29 | var p2 = Expression.Parameter(typeof(TSource), "src"); 30 | var p3 = Expression.Parameter(typeof(string).MakeByRefType(), "errMsg"); 31 | parameterTuple = new ParameterTuple(p1, p2, p3); 32 | opt = new Option(parameterTuple); 33 | } 34 | private RefFunc m_func; 35 | private Option opt = null; 36 | private ParameterTuple parameterTuple = null; 37 | private Dictionary _map = new Dictionary(); 38 | private NullsafeQueryRewriter nullsafeQueryRewriter = new NullsafeQueryRewriter(); 39 | private Func nullsafeQueryFunc = null; 40 | private Dictionary _typeConvertMap = new Dictionary(); 41 | 42 | public AutoCopy ForMember(Expression> dest, Func, Expression> src) 43 | { 44 | //Expression body = src; 45 | //if(body is LambdaExpression) 46 | //{ 47 | // body = ((LambdaExpression)body).Body; 48 | //} 49 | //if(body.NodeType!= ExpressionType.MemberAccess) 50 | //{ 51 | // throw new InvalidOperationException(); 52 | //} 53 | //var p = (PropertyInfo)((MemberExpression)body).Member; 54 | var p = FindProperty(dest) as PropertyInfo; 55 | var expression = src(opt); 56 | _map[p] = expression; 57 | return this; 58 | } 59 | public AutoCopy ForMember(Expression> dest, Func, Func> src) 60 | { 61 | var p = FindProperty(dest) as PropertyInfo; 62 | var func = src(opt); 63 | Expression expression = null; 64 | try 65 | { 66 | var exp = func.Decompile(); 67 | expression = ParameterReplacer.Replace(exp.Body, new ParameterExpression[] { parameterTuple.Source }, new ParameterExpression[] { parameterTuple.Source }); 68 | } 69 | catch 70 | { 71 | expression = Expression.Call(Expression.Constant(func.Target), func.Method, parameterTuple.Source); 72 | } 73 | 74 | _map[p] = expression; 75 | return this; 76 | } 77 | public AutoCopy ForTypeConvert(Expression> converter) 78 | { 79 | Type src = typeof(T1); 80 | Type dst = typeof(T2); 81 | if (src == dst) 82 | throw new Exception($"{src.Name}与{dst.Name}类型相同"); 83 | TypeTuple tuple = new TypeTuple(src, dst); 84 | if (_typeConvertMap.ContainsKey(tuple)) 85 | throw new Exception($"已经存在{src.Name}到{dst.Name}的转换"); 86 | Expression body = converter; 87 | if (body is LambdaExpression) 88 | { 89 | body = ((LambdaExpression)body).Body; 90 | if (body == null) 91 | throw new Exception("lambda表达式不能为空"); 92 | var method = body as MethodCallExpression; 93 | MethodInfo methodInfo = null; 94 | if (method == null) 95 | { 96 | methodInfo = converter.Compile().Method; 97 | } 98 | else 99 | { 100 | methodInfo = method.Method; 101 | } 102 | if (methodInfo == null) 103 | throw new Exception("获取不到lambda表达式中调用的方法"); 104 | _typeConvertMap.Add(tuple, methodInfo); 105 | } 106 | else 107 | { 108 | throw new Exception("不是合法的lambda表达式"); 109 | } 110 | return this; 111 | } 112 | private LambdaExpression RegisterCore(bool enableNullSafe) 113 | { 114 | if (this.Lambda == null) 115 | { 116 | nullsafeQueryFunc = (exp) => enableNullSafe ? nullsafeQueryRewriter.visit(exp) : exp; 117 | var propertyInfos = typeof(TDest).GetProperties(BindingFlags.Instance | BindingFlags.Public); 118 | var destPropertyInfos = propertyInfos.Where(p => p.GetCustomAttribute(true) == null); 119 | hasReturnLabel = propertyInfos.Where(p => p.GetCustomAttribute(true) != null).FirstOrDefault() != null; 120 | LabelTarget returnTarget = Expression.Label(typeof(bool)); 121 | //var dstPropertyInfos = typeof(D).GetProperties(BindingFlags.Instance | BindingFlags.Public); 122 | 123 | List list = new List(); 124 | List initExprs = new List(); 125 | List variables = new List(); 126 | initExprs.Add(Expression.Assign(parameterTuple.ErrorMsg, Expression.Constant(null, typeof(string)))); 127 | initExprs.Add(Expression.Assign(parameterTuple.Destination, Expression.Coalesce(parameterTuple.Destination, Expression.New(typeof(TDest))))); 128 | foreach (var destPropertyInfo in destPropertyInfos) 129 | { 130 | if (!destPropertyInfo.CanWrite) 131 | { 132 | continue; 133 | } 134 | Expression exp, test = null; 135 | ParameterExpression @var; 136 | bool ifTrue = false; 137 | string sourceName = destPropertyInfo.GetCustomAttribute()?.MapName ?? destPropertyInfo.Name; 138 | if (!_map.TryGetValue(destPropertyInfo, out exp)) 139 | { 140 | if (!Provider.TryGetExpression(sourceName, parameterTuple.Source, destPropertyInfo.PropertyType, out exp, out @var, out test, out ifTrue)) 141 | { 142 | continue; 143 | } 144 | if (@var != null) 145 | { 146 | variables.Add(@var); 147 | } 148 | } 149 | if (destPropertyInfo.PropertyType != exp.Type) 150 | { 151 | TypeTuple typeTuple = new TypeTuple(exp.Type, destPropertyInfo.PropertyType); 152 | MethodInfo m; 153 | if (_typeConvertMap.TryGetValue(typeTuple, out m)) 154 | { 155 | exp = Expression.Call(m, exp); 156 | list.Add(Expression.Assign(Expression.MakeMemberAccess(parameterTuple.Destination, destPropertyInfo), nullsafeQueryFunc(exp))); 157 | } 158 | else 159 | { 160 | Action, ParameterExpression, PropertyInfo, Func> act; 161 | ParameterExpression variable; 162 | //ConvertType 163 | if (!TypeConverter.TryConvert(exp, exp.Type, destPropertyInfo.PropertyType, out act, out variable)) 164 | { 165 | continue; 166 | } 167 | if (act == null) 168 | continue; 169 | act(list, parameterTuple.Destination, destPropertyInfo, nullsafeQueryFunc); 170 | if (variable != null) 171 | { 172 | variables.Add(variable); 173 | } 174 | } 175 | } 176 | else 177 | { 178 | exp = ParameterReplacer.Replace(exp, new[] { Expression.Parameter(typeof(string), "name") }, new Expression[] { Expression.Constant(sourceName) }); 179 | list.Add(Expression.Assign(Expression.MakeMemberAccess(parameterTuple.Destination, destPropertyInfo), nullsafeQueryFunc(exp))); 180 | } 181 | //表示表达式需要进行ifTrue的判断 182 | if (ifTrue && test != null) 183 | { 184 | //对当前表达式进行包装 185 | var tempExp = list[list.Count - 1]; 186 | tempExp = Expression.IfThen(test, tempExp); 187 | list[list.Count - 1] = tempExp; 188 | } 189 | //check if the property has the CopyRequiredAttribute 190 | var copyRequired = destPropertyInfo.GetCustomAttribute(); 191 | if (copyRequired != null) 192 | { 193 | var tempExp = list[list.Count - 1]; 194 | if (tempExp.NodeType == ExpressionType.Conditional) 195 | { 196 | Expression falseBody = Expression.Block( 197 | Expression.Assign(parameterTuple.ErrorMsg, Expression.Constant(string.Format(copyRequired.MsgFormat, sourceName))), 198 | Expression.Return(returnTarget, ReturnFalse) 199 | ); 200 | tempExp = new ConditionFalseRewriter(falseBody).Visit(tempExp); 201 | list[list.Count - 1] = tempExp; 202 | } 203 | else if (tempExp.NodeType == ExpressionType.Assign && ((BinaryExpression)tempExp).Right.NodeType == ExpressionType.Invoke) 204 | { 205 | //if(!string.IsNullOrEmpty(errmsg)){ $falseBody } 206 | var e = Expression.IfThen(Expression.NotEqual(parameterTuple.ErrorMsg, Expression.Constant(null, typeof(string))), Expression.Return(returnTarget, ReturnFalse)); 207 | list.Add(e); 208 | } 209 | 210 | } 211 | } 212 | if (!hasReturnLabel) 213 | list.Add(ReturnTrue); 214 | else 215 | list.Add(Expression.Return(returnTarget, ReturnTrue)); 216 | BlockExpression body = null; 217 | if (variables.Count == 0) 218 | body = Expression.Block(list); 219 | else 220 | body = Expression.Block(variables, list); 221 | this.Body = body; 222 | var parExcep = Expression.Parameter(typeof(Exception), "ex"); 223 | var catchBlock = Expression.Block( 224 | Expression.Assign(parameterTuple.ErrorMsg, Expression.MakeMemberAccess(parExcep, Utilities.StaticReflection.GetMemberInfo((Exception ex) => ex.Message))), 225 | !hasReturnLabel ? (Expression)ReturnFalse : (Expression)Expression.Return(returnTarget, ReturnFalse) 226 | ); 227 | var body2 = Expression.TryCatch(body, Expression.Catch(parExcep, catchBlock)); 228 | 229 | var lambdaExpression = Expression.Lambda(Expression.Block(initExprs.Concat(!hasReturnLabel ? new Expression[] { body2 } : new Expression[] { body2, Expression.Label(returnTarget, ReturnFalse) })), parameterTuple.Collect()); 230 | 231 | this.Lambda = lambdaExpression; 232 | } 233 | return this.Lambda; 234 | } 235 | public void Register(bool enableNullSafe = false) 236 | { 237 | var lambdaExpression = RegisterCore(enableNullSafe); 238 | try 239 | { 240 | IsFastMode = true; 241 | var assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly( 242 | new AssemblyName("AutoCopyAssembly_" + Guid.NewGuid().ToString("N")), 243 | AssemblyBuilderAccess.Run); 244 | 245 | var moduleBuilder = assemblyBuilder.DefineDynamicModule("Module"); 246 | 247 | var typeBuilder = moduleBuilder.DefineType("AutoCopy_" + Guid.NewGuid().ToString("N"), 248 | TypeAttributes.Public); 249 | 250 | var methodBuilder = typeBuilder.DefineMethod("ShallowCopy", 251 | MethodAttributes.Public | MethodAttributes.Static); 252 | lambdaExpression.CompileToMethod(methodBuilder); 253 | 254 | var resultingType = typeBuilder.CreateType(); 255 | 256 | var function = Delegate.CreateDelegate(lambdaExpression.Type, 257 | resultingType.GetMethod("ShallowCopy")); 258 | m_func = function as RefFunc; 259 | } 260 | catch 261 | { 262 | //当使用ResolveUsing方法时,如果lambda表达式含有语句体,则try中编译失败; 263 | //还有一种情况是使用MapFrom方法时,里面调用了外部变量的方法,则try中依然会编译失败 264 | IsFastMode = false; 265 | m_func = lambdaExpression.Compile() as RefFunc; 266 | } 267 | 268 | 269 | //m_func = Expression.Lambda(body2, p1, p2, p3).Compile(); 270 | //m_func = function as RefFunc; 271 | } 272 | public bool ShallowCopy(TSource src, TDest dst) 273 | { 274 | string errMsg; 275 | return m_func(ref dst, src, out errMsg); 276 | } 277 | public TDest Map(TSource source) 278 | { 279 | TDest t = default(TDest); 280 | string errMsg; 281 | if (!m_func(ref t, source, out errMsg)) 282 | { 283 | throw new Exception(errMsg); 284 | } 285 | return t; 286 | } 287 | public bool TryMap(TSource source, out TDest dest, out string errMsg) 288 | { 289 | errMsg = string.Empty; 290 | dest = default(TDest); 291 | return m_func(ref dest, source, out errMsg); 292 | } 293 | public TargetExpressionProviderBase Provider { get; set; } = new DefaultPropertyExpressionProvider(typeof(TSource)); 294 | public LambdaExpression Lambda 295 | { 296 | get; 297 | private set; 298 | } 299 | public BlockExpression Body 300 | { 301 | get; 302 | private set; 303 | } 304 | public bool IsFastMode 305 | { 306 | get; 307 | private set; 308 | } 309 | internal bool hasReturnLabel 310 | { 311 | get; 312 | private set; 313 | } 314 | } 315 | } 316 | -------------------------------------------------------------------------------- /AutoCopyLib/AutoCopyLib.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {C2685DAB-9618-4FDC-8E85-248E1069AC39} 8 | Library 9 | Properties 10 | AutoCopyLib 11 | AutoCopyLib 12 | v4.5 13 | 512 14 | 15 | 16 | true 17 | full 18 | false 19 | bin\Debug\ 20 | DEBUG;TRACE 21 | prompt 22 | 4 23 | 24 | 25 | pdbonly 26 | true 27 | bin\Release\ 28 | TRACE 29 | prompt 30 | 4 31 | 32 | 33 | 34 | False 35 | .\DelegateDecompiler.dll 36 | 37 | 38 | False 39 | .\Mono.Reflection.dll 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 89 | -------------------------------------------------------------------------------- /AutoCopyLib/DefaultPropertyExpressionProvider.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Linq; 3 | using System.Linq.Expressions; 4 | using System.Reflection; 5 | 6 | namespace AutoCopyLib 7 | { 8 | public sealed class DefaultPropertyExpressionProvider : TargetExpressionProviderBase 9 | { 10 | public override bool TryGetExpression(string name, ParameterExpression parameter, Type destType, out Expression exp, out ParameterExpression variable, out Expression test, out bool ifTrue) 11 | { 12 | exp = null; 13 | test = null; 14 | variable = null; 15 | ifTrue = false; 16 | var dstPropertyInfo = _infos.Where(p => p.Name.Equals(name, StringComparison.OrdinalIgnoreCase)).FirstOrDefault(); 17 | if (dstPropertyInfo == null || !dstPropertyInfo.CanRead) 18 | return false; 19 | exp = Expression.MakeMemberAccess(parameter, dstPropertyInfo); 20 | return true; 21 | } 22 | private PropertyInfo[] _infos; 23 | 24 | public DefaultPropertyExpressionProvider(Type targetType) : base(targetType) 25 | { 26 | _infos = targetType.GetProperties(BindingFlags.Instance | BindingFlags.Public); 27 | } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /AutoCopyLib/DelegateDecompiler.dll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ClockGet/AutoCopy/e16cfe0471cebb0394d96a953de7cd9989167fe5/AutoCopyLib/DelegateDecompiler.dll -------------------------------------------------------------------------------- /AutoCopyLib/FastExpressionCompiler.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Linq.Expressions; 5 | using System.Reflection; 6 | using System.Reflection.Emit; 7 | 8 | namespace FastExpressionCompiler 9 | { 10 | /// Compiles expression to delegate by emitting the IL directly. 11 | /// The emitter is ~20 times faster than Expression.Compile. 12 | public static partial class ExpressionCompiler 13 | { 14 | /// First tries to compile fast and if failed (null result), then falls back to Expression.Compile. 15 | /// Type of compiled delegate return result. 16 | /// Expr to compile. 17 | /// Compiled delegate. 18 | public static Func Compile(Expression> lambdaExpr) 19 | { 20 | return TryCompile>(lambdaExpr.Body, lambdaExpr.Parameters, _emptyTypes, typeof(T)) 21 | ?? lambdaExpr.Compile(); 22 | } 23 | 24 | /// Compiles lambda expression to . 25 | /// The compatible delegate type, otherwise case will throw. 26 | /// Lambda expression to compile. 27 | /// Compiled delegate. 28 | public static TDelegate Compile(LambdaExpression lambdaExpr) 29 | where TDelegate : class 30 | { 31 | return TryCompile(lambdaExpr) ?? (TDelegate)(object)lambdaExpr.Compile(); 32 | } 33 | 34 | /// Tries to compile lambda expression to . 35 | /// The compatible delegate type, otherwise case will throw. 36 | /// Lambda expression to compile. 37 | /// Compiled delegate. 38 | public static TDelegate TryCompile(LambdaExpression lambdaExpr) 39 | where TDelegate : class 40 | { 41 | var paramExprs = lambdaExpr.Parameters; 42 | var paramTypes = GetParamExprTypes(paramExprs); 43 | var expr = lambdaExpr.Body; 44 | return TryCompile(expr, paramExprs, paramTypes, expr.Type); 45 | } 46 | 47 | private static Type[] GetParamExprTypes(IList paramExprs) 48 | { 49 | var paramsCount = paramExprs.Count; 50 | if (paramsCount == 0) 51 | return _emptyTypes; 52 | 53 | if (paramsCount == 1) 54 | return new[] { paramExprs[0].Type }; 55 | 56 | var paramTypes = new Type[paramsCount]; 57 | for (var i = 0; i < paramTypes.Length; i++) 58 | paramTypes[i] = paramExprs[i].Type; 59 | return paramTypes; 60 | } 61 | 62 | /// Compiles expression to delegate by emitting the IL. 63 | /// If sub-expressions are not supported by emitter, then the method returns null. 64 | /// The usage should be calling the method, if result is null then calling the Expression.Compile. 65 | /// Lambda body. 66 | /// Lambda parameter expressions. 67 | /// The types of parameters. 68 | /// The return type. 69 | /// Result delegate or null, if unable to compile. 70 | public static TDelegate TryCompile( 71 | Expression bodyExpr, 72 | IList paramExprs, 73 | Type[] paramTypes, 74 | Type returnType) where TDelegate : class 75 | { 76 | ClosureInfo ignored = null; 77 | return (TDelegate)TryCompile(ref ignored, 78 | typeof(TDelegate), paramTypes, returnType, bodyExpr, paramExprs); 79 | } 80 | 81 | private static object TryCompile(ref ClosureInfo closureInfo, 82 | Type delegateType, Type[] paramTypes, Type returnType, 83 | Expression bodyExpr, IList paramExprs) 84 | { 85 | if (!TryCollectBoundConstants(ref closureInfo, bodyExpr, paramExprs)) 86 | return null; 87 | 88 | if (closureInfo != null) 89 | closureInfo.ConstructClosure(); 90 | 91 | var method = GetDynamicMethod(paramTypes, returnType, closureInfo); 92 | 93 | var il = method.GetILGenerator(); 94 | 95 | if (!EmittingVisitor.TryEmit(bodyExpr, paramExprs, il, closureInfo)) 96 | return null; 97 | 98 | il.Emit(OpCodes.Ret); // emits return from generated method 99 | 100 | // create open delegate with closure object 101 | if (closureInfo == null) 102 | return method.CreateDelegate(delegateType); 103 | 104 | return method.CreateDelegate(delegateType, closureInfo.ClosureObject); 105 | } 106 | 107 | private static DynamicMethod GetDynamicMethod(Type[] paramTypes, Type returnType, ClosureInfo closureInfo) 108 | { 109 | if (closureInfo == null) 110 | return new DynamicMethod(string.Empty, returnType, paramTypes, 111 | typeof(ExpressionCompiler), skipVisibility: true); 112 | 113 | var closureType = closureInfo.ClosureObject.GetType(); 114 | var closureAndParamTypes = GetClosureAndParamTypes(paramTypes, closureType); 115 | 116 | return new DynamicMethod(string.Empty, returnType, closureAndParamTypes, closureType, skipVisibility: true); 117 | } 118 | 119 | private static Type[] GetClosureAndParamTypes(Type[] paramTypes, Type closureType) 120 | { 121 | var paramCount = paramTypes.Length; 122 | if (paramCount == 0) 123 | return new[] { closureType }; 124 | 125 | var closureAndParamTypes = new Type[paramCount + 1]; 126 | closureAndParamTypes[0] = closureType; 127 | if (paramCount == 1) 128 | closureAndParamTypes[1] = paramTypes[0]; 129 | else if (paramCount > 1) 130 | Array.Copy(paramTypes, 0, closureAndParamTypes, 1, paramCount); 131 | 132 | return closureAndParamTypes; 133 | } 134 | 135 | private sealed class ClosureInfo 136 | { 137 | public List ConstantExpressions { get; private set; } 138 | public List UsedParamExpressions { get; private set; } 139 | public List NestedLambdas { get; private set; } 140 | 141 | public FieldInfo[] Fields { get; private set; } 142 | 143 | public bool IsArray { get; private set; } 144 | 145 | public object ClosureObject { get; private set; } 146 | 147 | public int ConstantCount { get { return ConstantExpressions == null ? 0 : ConstantExpressions.Count; } } 148 | 149 | public int UsedParamCount { get { return UsedParamExpressions == null ? 0 : UsedParamExpressions.Count; } } 150 | 151 | public int NestedLambdaCount { get { return NestedLambdas == null ? 0 : NestedLambdas.Count; } } 152 | 153 | public void Add(ConstantExpression expr) 154 | { 155 | if (ConstantExpressions == null) 156 | ConstantExpressions = new List(); 157 | ConstantExpressions.Add(expr); 158 | } 159 | 160 | public void Add(ParameterExpression expr) 161 | { 162 | if (UsedParamExpressions == null) 163 | UsedParamExpressions = new List(); 164 | UsedParamExpressions.Add(expr); 165 | } 166 | 167 | public void Add(NestedLambdaInfo nestedLambdaInfo) 168 | { 169 | if (NestedLambdas == null) 170 | NestedLambdas = new List(); 171 | NestedLambdas.Add(nestedLambdaInfo); 172 | } 173 | 174 | public void ConstructClosure() 175 | { 176 | var constantCount = ConstantCount; 177 | var constantPlusParamCount = constantCount + UsedParamCount; 178 | var totalItemCount = constantPlusParamCount + NestedLambdaCount; 179 | 180 | var items = new object[totalItemCount]; 181 | 182 | // Deciding to create typed or array based closure, based on number of closed constants 183 | // Not null array of constant types means a typed closure can be created 184 | var typedClosureCreateMethods = Closure.TypedClosureCreateMethods; 185 | var constantTypes = totalItemCount <= typedClosureCreateMethods.Length ? new Type[totalItemCount] : null; 186 | 187 | if (ConstantExpressions != null) 188 | for (var i = 0; i < ConstantExpressions.Count; i++) 189 | { 190 | var constantExpr = ConstantExpressions[i]; 191 | items[i] = constantExpr.Value; 192 | if (constantTypes != null) 193 | constantTypes[i] = constantExpr.Type; 194 | } 195 | 196 | if (UsedParamExpressions != null) 197 | for (var i = 0; i < UsedParamExpressions.Count; i++) 198 | { 199 | items[constantCount + i] = null; 200 | if (constantTypes != null) 201 | constantTypes[constantCount + i] = UsedParamExpressions[i].Type; 202 | } 203 | 204 | if (NestedLambdas != null) 205 | for (var i = 0; i < NestedLambdas.Count; i++) 206 | { 207 | var lambda = NestedLambdas[i].Lambda; 208 | items[constantPlusParamCount + i] = lambda; 209 | if (constantTypes != null) 210 | constantTypes[constantPlusParamCount + i] = lambda.GetType(); 211 | } 212 | 213 | if (constantTypes != null) 214 | { 215 | var createClosureMethod = typedClosureCreateMethods[totalItemCount - 1]; 216 | var createClosure = createClosureMethod.MakeGenericMethod(constantTypes); 217 | 218 | var closure = createClosure.Invoke(null, items); 219 | 220 | var fields = closure.GetType().GetTypeInfo().DeclaredFields; 221 | var fieldsArray = fields as FieldInfo[] ?? fields.ToArray(); 222 | 223 | ClosureObject = closure; 224 | Fields = fieldsArray; 225 | } 226 | else 227 | { 228 | ClosureObject = new ArrayClosure(items); 229 | IsArray = true; 230 | } 231 | } 232 | } 233 | 234 | #region Closures 235 | 236 | internal static class Closure 237 | { 238 | public static readonly MethodInfo[] TypedClosureCreateMethods = 239 | typeof(Closure).GetTypeInfo().DeclaredMethods.ToArray(); 240 | 241 | public static Closure CreateClosure(T1 v1) 242 | { 243 | return new Closure(v1); 244 | } 245 | 246 | public static Closure CreateClosure(T1 v1, T2 v2) 247 | { 248 | return new Closure(v1, v2); 249 | } 250 | 251 | public static Closure CreateClosure(T1 v1, T2 v2, T3 v3) 252 | { 253 | return new Closure(v1, v2, v3); 254 | } 255 | 256 | public static Closure CreateClosure(T1 v1, T2 v2, T3 v3, T4 v4) 257 | { 258 | return new Closure(v1, v2, v3, v4); 259 | } 260 | 261 | public static Closure CreateClosure(T1 v1, T2 v2, T3 v3, T4 v4, 262 | T5 v5) 263 | { 264 | return new Closure(v1, v2, v3, v4, v5); 265 | } 266 | 267 | public static Closure CreateClosure(T1 v1, T2 v2, T3 v3, 268 | T4 v4, T5 v5, T6 v6) 269 | { 270 | return new Closure(v1, v2, v3, v4, v5, v6); 271 | } 272 | 273 | public static Closure CreateClosure(T1 v1, T2 v2, 274 | T3 v3, T4 v4, T5 v5, T6 v6, T7 v7) 275 | { 276 | return new Closure(v1, v2, v3, v4, v5, v6, v7); 277 | } 278 | 279 | public static Closure CreateClosure( 280 | T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8) 281 | { 282 | return new Closure(v1, v2, v3, v4, v5, v6, v7, v8); 283 | } 284 | 285 | public static Closure CreateClosure( 286 | T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9) 287 | { 288 | return new Closure(v1, v2, v3, v4, v5, v6, v7, v8, v9); 289 | } 290 | 291 | public static Closure CreateClosure( 292 | T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10) 293 | { 294 | return new Closure(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10); 295 | } 296 | } 297 | 298 | internal sealed class Closure 299 | { 300 | public T1 V1; 301 | 302 | public Closure(T1 v1) 303 | { 304 | V1 = v1; 305 | } 306 | } 307 | 308 | internal sealed class Closure 309 | { 310 | public T1 V1; 311 | public T2 V2; 312 | 313 | public Closure(T1 v1, T2 v2) 314 | { 315 | V1 = v1; 316 | V2 = v2; 317 | } 318 | } 319 | 320 | internal sealed class Closure 321 | { 322 | public T1 V1; 323 | public T2 V2; 324 | public T3 V3; 325 | 326 | public Closure(T1 v1, T2 v2, T3 v3) 327 | { 328 | V1 = v1; 329 | V2 = v2; 330 | V3 = v3; 331 | } 332 | } 333 | 334 | internal sealed class Closure 335 | { 336 | public T1 V1; 337 | public T2 V2; 338 | public T3 V3; 339 | public T4 V4; 340 | 341 | public Closure(T1 v1, T2 v2, T3 v3, T4 v4) 342 | { 343 | V1 = v1; 344 | V2 = v2; 345 | V3 = v3; 346 | V4 = v4; 347 | } 348 | } 349 | 350 | internal sealed class Closure 351 | { 352 | public T1 V1; 353 | public T2 V2; 354 | public T3 V3; 355 | public T4 V4; 356 | public T5 V5; 357 | 358 | public Closure(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5) 359 | { 360 | V1 = v1; 361 | V2 = v2; 362 | V3 = v3; 363 | V4 = v4; 364 | V5 = v5; 365 | } 366 | } 367 | 368 | internal sealed class Closure 369 | { 370 | public T1 V1; 371 | public T2 V2; 372 | public T3 V3; 373 | public T4 V4; 374 | public T5 V5; 375 | public T6 V6; 376 | 377 | public Closure(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6) 378 | { 379 | V1 = v1; 380 | V2 = v2; 381 | V3 = v3; 382 | V4 = v4; 383 | V5 = v5; 384 | V6 = v6; 385 | } 386 | } 387 | 388 | internal sealed class Closure 389 | { 390 | public T1 V1; 391 | public T2 V2; 392 | public T3 V3; 393 | public T4 V4; 394 | public T5 V5; 395 | public T6 V6; 396 | public T7 V7; 397 | 398 | public Closure(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7) 399 | { 400 | V1 = v1; 401 | V2 = v2; 402 | V3 = v3; 403 | V4 = v4; 404 | V5 = v5; 405 | V6 = v6; 406 | V7 = v7; 407 | } 408 | } 409 | 410 | internal sealed class Closure 411 | { 412 | public T1 V1; 413 | public T2 V2; 414 | public T3 V3; 415 | public T4 V4; 416 | public T5 V5; 417 | public T6 V6; 418 | public T7 V7; 419 | public T8 V8; 420 | 421 | public Closure(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8) 422 | { 423 | V1 = v1; 424 | V2 = v2; 425 | V3 = v3; 426 | V4 = v4; 427 | V5 = v5; 428 | V6 = v6; 429 | V7 = v7; 430 | V8 = v8; 431 | } 432 | } 433 | 434 | internal sealed class Closure 435 | { 436 | public T1 V1; 437 | public T2 V2; 438 | public T3 V3; 439 | public T4 V4; 440 | public T5 V5; 441 | public T6 V6; 442 | public T7 V7; 443 | public T8 V8; 444 | public T9 V9; 445 | 446 | public Closure(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9) 447 | { 448 | V1 = v1; 449 | V2 = v2; 450 | V3 = v3; 451 | V4 = v4; 452 | V5 = v5; 453 | V6 = v6; 454 | V7 = v7; 455 | V8 = v8; 456 | V9 = v9; 457 | } 458 | } 459 | 460 | internal sealed class Closure 461 | { 462 | public T1 V1; 463 | public T2 V2; 464 | public T3 V3; 465 | public T4 V4; 466 | public T5 V5; 467 | public T6 V6; 468 | public T7 V7; 469 | public T8 V8; 470 | public T9 V9; 471 | public T10 V10; 472 | 473 | public Closure(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10) 474 | { 475 | V1 = v1; 476 | V2 = v2; 477 | V3 = v3; 478 | V4 = v4; 479 | V5 = v5; 480 | V6 = v6; 481 | V7 = v7; 482 | V8 = v8; 483 | V9 = v9; 484 | V10 = v10; 485 | } 486 | } 487 | 488 | internal sealed class ArrayClosure 489 | { 490 | public readonly object[] Constants; 491 | public static FieldInfo ArrayField = typeof(ArrayClosure).GetTypeInfo().DeclaredFields.First(f => !f.IsStatic); 492 | 493 | public ArrayClosure(object[] constants) 494 | { 495 | Constants = constants; 496 | } 497 | } 498 | 499 | #endregion 500 | 501 | #region Collect Bound Constants 502 | 503 | private sealed class NestedLambdaInfo 504 | { 505 | public readonly object Lambda; 506 | public readonly Expression LambdaExpr; // to find the lambda in bigger parent expression 507 | public readonly ClosureInfo ClosureInfo; 508 | 509 | public NestedLambdaInfo(object lambda, Expression lambdaExpr, ClosureInfo closureInfo) 510 | { 511 | Lambda = lambda; 512 | LambdaExpr = lambdaExpr; 513 | ClosureInfo = closureInfo; 514 | } 515 | } 516 | 517 | private static bool IsBoundConstant(object value) 518 | { 519 | if (value == null) 520 | return false; 521 | 522 | var typeInfo = value.GetType().GetTypeInfo(); 523 | return !typeInfo.IsPrimitive 524 | && !(value is string) 525 | && !(value is Type) 526 | && !typeInfo.IsEnum; 527 | } 528 | 529 | private static readonly Type[] _emptyTypes = new Type[0]; 530 | 531 | // @paramExprs is required for nested lambda compilation 532 | private static bool TryCollectBoundConstants(ref ClosureInfo closure, Expression expr, IList paramExprs) 533 | { 534 | if (expr == null) 535 | return false; 536 | 537 | switch (expr.NodeType) 538 | { 539 | case ExpressionType.Constant: 540 | var constantExpr = (ConstantExpression)expr; 541 | var constantValue = constantExpr.Value; 542 | 543 | if (constantValue is Delegate || 544 | IsBoundConstant(constantValue)) 545 | { 546 | closure = closure ?? new ClosureInfo(); 547 | closure.Add(constantExpr); 548 | } 549 | 550 | break; 551 | 552 | case ExpressionType.Parameter: 553 | // if parameter is used But no passed (not in parameter expressions) 554 | // it means parameter is provided by outer lambda and should be put in closure for current lambda 555 | var paramExpr = (ParameterExpression)expr; 556 | if (paramExprs.IndexOf(paramExpr) == -1) 557 | { 558 | closure = closure ?? new ClosureInfo(); 559 | closure.Add(paramExpr); 560 | } 561 | break; 562 | 563 | case ExpressionType.Call: 564 | var methodCallExpr = (MethodCallExpression)expr; 565 | var methodOwnerExpr = methodCallExpr.Object; 566 | 567 | return (methodOwnerExpr == null 568 | || TryCollectBoundConstants(ref closure, methodOwnerExpr, paramExprs)) 569 | && TryCollectBoundConstants(ref closure, methodCallExpr.Arguments, paramExprs); 570 | 571 | case ExpressionType.MemberAccess: 572 | var memberExpr = ((MemberExpression)expr).Expression; 573 | return memberExpr == null 574 | || TryCollectBoundConstants(ref closure, memberExpr, paramExprs); 575 | 576 | case ExpressionType.New: 577 | return TryCollectBoundConstants(ref closure, ((NewExpression)expr).Arguments, paramExprs); 578 | 579 | case ExpressionType.NewArrayInit: 580 | return TryCollectBoundConstants(ref closure, ((NewArrayExpression)expr).Expressions, paramExprs); 581 | 582 | // property initializer 583 | case ExpressionType.MemberInit: 584 | var memberInitExpr = (MemberInitExpression)expr; 585 | if (!TryCollectBoundConstants(ref closure, memberInitExpr.NewExpression, paramExprs)) 586 | return false; 587 | 588 | var memberBindings = memberInitExpr.Bindings; 589 | for (var i = 0; i < memberBindings.Count; ++i) 590 | { 591 | var memberBinding = memberBindings[i]; 592 | if (memberBinding.BindingType == MemberBindingType.Assignment && 593 | !TryCollectBoundConstants(ref closure, ((MemberAssignment)memberBinding).Expression, paramExprs)) 594 | return false; 595 | } 596 | break; 597 | 598 | // nested lambda 599 | case ExpressionType.Lambda: 600 | 601 | // 1. Try to compile nested lambda in place 602 | // 2. Check that parameters used in compiled lambda are passed or closed by outer lambda 603 | // 3. Add the compiled lambda to closure of outer lambda for later invocation 604 | 605 | var lambdaExpr = (LambdaExpression)expr; 606 | var lambdaParamExprs = lambdaExpr.Parameters; 607 | var paramTypes = GetParamExprTypes(lambdaParamExprs); 608 | 609 | ClosureInfo nestedClosure = null; 610 | var lambda = TryCompile(ref nestedClosure, 611 | lambdaExpr.Type, paramTypes, lambdaExpr.Body.Type, lambdaExpr.Body, lambdaParamExprs); 612 | 613 | if (lambda == null) 614 | return false; 615 | 616 | var lambdaInfo = new NestedLambdaInfo(lambda, lambdaExpr, nestedClosure); 617 | 618 | closure = closure ?? new ClosureInfo(); 619 | closure.Add(lambdaInfo); 620 | 621 | // if nested parameter is no matched with any outer parameter, that ensure it goes to outer closure 622 | if (nestedClosure != null && nestedClosure.UsedParamExpressions != null) 623 | { 624 | var nestedClosedParams = nestedClosure.UsedParamExpressions; 625 | for (var i = 0; i < nestedClosedParams.Count; i++) 626 | { 627 | var nestedClosedParamExpr = nestedClosedParams[i]; 628 | if (paramExprs.Count == 0 || 629 | paramExprs.IndexOf(nestedClosedParamExpr) == -1) 630 | { 631 | closure.Add(nestedClosedParamExpr); 632 | } 633 | } 634 | } 635 | 636 | break; 637 | 638 | case ExpressionType.Invoke: 639 | var invocationExpr = (InvocationExpression)expr; 640 | return TryCollectBoundConstants(ref closure, invocationExpr.Expression, paramExprs) 641 | && TryCollectBoundConstants(ref closure, invocationExpr.Arguments, paramExprs); 642 | 643 | case ExpressionType.Conditional: 644 | var conditionalExpr = (ConditionalExpression)expr; 645 | return TryCollectBoundConstants(ref closure, conditionalExpr.Test, paramExprs) 646 | && TryCollectBoundConstants(ref closure, conditionalExpr.IfTrue, paramExprs) 647 | && TryCollectBoundConstants(ref closure, conditionalExpr.IfFalse, paramExprs); 648 | 649 | default: 650 | var unaryExpr = expr as UnaryExpression; 651 | if (unaryExpr != null) 652 | return TryCollectBoundConstants(ref closure, unaryExpr.Operand, paramExprs); 653 | 654 | var binaryExpr = expr as BinaryExpression; 655 | if (binaryExpr != null) 656 | return TryCollectBoundConstants(ref closure, binaryExpr.Left, paramExprs) 657 | && TryCollectBoundConstants(ref closure, binaryExpr.Right, paramExprs); 658 | break; 659 | } 660 | 661 | return true; 662 | } 663 | 664 | private static bool TryCollectBoundConstants(ref ClosureInfo closure, IList exprs, IList paramExprs) 665 | { 666 | var count = exprs.Count; 667 | for (var i = 0; i < count; i++) 668 | if (!TryCollectBoundConstants(ref closure, exprs[i], paramExprs)) 669 | return false; 670 | return true; 671 | } 672 | 673 | #endregion 674 | 675 | /// Supports emitting of selected expressions, e.g. lambdaExpr are not supported yet. 676 | /// When emitter find not supported expression it will return false from , so I could fallback 677 | /// to normal and slow Expression.Compile. 678 | private static class EmittingVisitor 679 | { 680 | private static readonly MethodInfo _getDelegateTargetProperty = 681 | typeof(Delegate).GetTypeInfo().DeclaredMethods.First(p => p.Name == "get_Target"); 682 | 683 | public static bool TryEmit(Expression expr, IList paramExprs, ILGenerator il, ClosureInfo closure) 684 | { 685 | switch (expr.NodeType) 686 | { 687 | case ExpressionType.Parameter: 688 | return EmitParameter((ParameterExpression)expr, paramExprs, il, closure); 689 | case ExpressionType.Convert: 690 | return EmitConvert((UnaryExpression)expr, paramExprs, il, closure); 691 | case ExpressionType.ArrayIndex: 692 | return EmitArrayIndex((BinaryExpression)expr, paramExprs, il, closure); 693 | case ExpressionType.Constant: 694 | return EmitConstant((ConstantExpression)expr, il, closure); 695 | case ExpressionType.New: 696 | return EmitNew((NewExpression)expr, paramExprs, il, closure); 697 | case ExpressionType.NewArrayInit: 698 | return EmitNewArray((NewArrayExpression)expr, paramExprs, il, closure); 699 | case ExpressionType.MemberInit: 700 | return EmitMemberInit((MemberInitExpression)expr, paramExprs, il, closure); 701 | case ExpressionType.Call: 702 | return EmitMethodCall((MethodCallExpression)expr, paramExprs, il, closure); 703 | case ExpressionType.MemberAccess: 704 | return EmitMemberAccess((MemberExpression)expr, paramExprs, il, closure); 705 | 706 | case ExpressionType.Lambda: 707 | return EmitNestedLambda((LambdaExpression)expr, paramExprs, il, closure); 708 | 709 | case ExpressionType.Invoke: 710 | return EmitInvokeLambda((InvocationExpression)expr, paramExprs, il, closure); 711 | 712 | case ExpressionType.GreaterThan: 713 | case ExpressionType.GreaterThanOrEqual: 714 | case ExpressionType.LessThan: 715 | case ExpressionType.LessThanOrEqual: 716 | case ExpressionType.Equal: 717 | case ExpressionType.NotEqual: 718 | return EmitComparison((BinaryExpression)expr, paramExprs, il, closure); 719 | 720 | case ExpressionType.AndAlso: 721 | case ExpressionType.OrElse: 722 | return EmitLogicalOperator((BinaryExpression)expr, paramExprs, il, closure); 723 | 724 | case ExpressionType.Conditional: 725 | return EmitTernararyOperator((ConditionalExpression)expr, paramExprs, il, closure); 726 | 727 | //case ExpressionType.Coalesce: 728 | default: 729 | return false; 730 | } 731 | } 732 | 733 | private static bool EmitParameter(ParameterExpression p, IList ps, ILGenerator il, ClosureInfo closure) 734 | { 735 | var paramIndex = ps.IndexOf(p); 736 | 737 | // if parameter is passed, then just load it on stack 738 | if (paramIndex != -1) 739 | { 740 | if (closure != null) 741 | paramIndex += 1; // shift parameter indices by one, because the first one will be closure 742 | LoadParamArg(il, paramIndex); 743 | return true; 744 | } 745 | 746 | // Otherwise (parameter isn't passed) then it is probably passed into outer lambda, 747 | // so it should be loaded from closure 748 | if (closure == null) 749 | return false; 750 | 751 | var usedParamIndex = closure.UsedParamExpressions.IndexOf(p); 752 | if (usedParamIndex == -1) 753 | return false; // what??? no chance 754 | 755 | var closureItemIndex = usedParamIndex + closure.ConstantCount; 756 | LoadClosureFieldOrItem(il, closure, closureItemIndex, p.Type); 757 | return true; 758 | } 759 | 760 | private static void LoadParamArg(ILGenerator il, int paramIndex) 761 | { 762 | switch (paramIndex) 763 | { 764 | case 0: 765 | il.Emit(OpCodes.Ldarg_0); 766 | break; 767 | case 1: 768 | il.Emit(OpCodes.Ldarg_1); 769 | break; 770 | case 2: 771 | il.Emit(OpCodes.Ldarg_2); 772 | break; 773 | case 3: 774 | il.Emit(OpCodes.Ldarg_3); 775 | break; 776 | default: 777 | if (paramIndex <= byte.MaxValue) 778 | il.Emit(OpCodes.Ldarg_S, (byte)paramIndex); 779 | else 780 | il.Emit(OpCodes.Ldarg, paramIndex); 781 | break; 782 | } 783 | } 784 | 785 | private static bool EmitBinary(BinaryExpression e, IList ps, ILGenerator il, ClosureInfo closure) 786 | { 787 | return TryEmit(e.Left, ps, il, closure) 788 | && TryEmit(e.Right, ps, il, closure); 789 | } 790 | 791 | private static bool EmitMany(IList es, IList ps, ILGenerator il, ClosureInfo closure) 792 | { 793 | for (int i = 0, n = es.Count; i < n; i++) 794 | if (!TryEmit(es[i], ps, il, closure)) 795 | return false; 796 | return true; 797 | } 798 | 799 | private static bool EmitConvert(UnaryExpression e, IList ps, ILGenerator il, ClosureInfo closure) 800 | { 801 | if (!TryEmit(e.Operand, ps, il, closure)) 802 | return false; 803 | 804 | var targetType = e.Type; 805 | if (targetType == typeof(object)) 806 | return false; 807 | 808 | if (targetType == typeof(int)) 809 | il.Emit(OpCodes.Conv_I4); 810 | else if (targetType == typeof(float)) 811 | il.Emit(OpCodes.Conv_R4); 812 | else if (targetType == typeof(uint)) 813 | il.Emit(OpCodes.Conv_U4); 814 | else if (targetType == typeof(sbyte)) 815 | il.Emit(OpCodes.Conv_I1); 816 | else if (targetType == typeof(byte)) 817 | il.Emit(OpCodes.Conv_U1); 818 | else if (targetType == typeof(short)) 819 | il.Emit(OpCodes.Conv_I2); 820 | else if (targetType == typeof(ushort)) 821 | il.Emit(OpCodes.Conv_U2); 822 | else if (targetType == typeof(long)) 823 | il.Emit(OpCodes.Conv_I8); 824 | else if (targetType == typeof(ulong)) 825 | il.Emit(OpCodes.Conv_U8); 826 | else if (targetType == typeof(double)) 827 | il.Emit(OpCodes.Conv_R8); 828 | else 829 | il.Emit(OpCodes.Castclass, targetType); 830 | 831 | return true; 832 | } 833 | 834 | private static bool EmitConstant(ConstantExpression e, ILGenerator il, ClosureInfo closure) 835 | { 836 | var constant = e.Value; 837 | if (constant == null) 838 | { 839 | il.Emit(OpCodes.Ldnull); 840 | return true; 841 | } 842 | 843 | var constantActualType = constant.GetType(); 844 | if (constantActualType.GetTypeInfo().IsEnum) 845 | constantActualType = Enum.GetUnderlyingType(constantActualType); 846 | 847 | if (constantActualType == typeof(int)) 848 | { 849 | EmitLoadConstantInt(il, (int)constant); 850 | } 851 | else if (constantActualType == typeof(char)) 852 | { 853 | EmitLoadConstantInt(il, (char)constant); 854 | } 855 | else if (constantActualType == typeof(short)) 856 | { 857 | EmitLoadConstantInt(il, (short)constant); 858 | } 859 | else if (constantActualType == typeof(byte)) 860 | { 861 | EmitLoadConstantInt(il, (byte)constant); 862 | } 863 | else if (constantActualType == typeof(ushort)) 864 | { 865 | EmitLoadConstantInt(il, (ushort)constant); 866 | } 867 | else if (constantActualType == typeof(sbyte)) 868 | { 869 | EmitLoadConstantInt(il, (sbyte)constant); 870 | } 871 | else if (constantActualType == typeof(uint)) 872 | { 873 | unchecked 874 | { 875 | EmitLoadConstantInt(il, (int)(uint)constant); 876 | } 877 | } 878 | else if (constantActualType == typeof(long)) 879 | { 880 | il.Emit(OpCodes.Ldc_I8, (long)constant); 881 | } 882 | else if (constantActualType == typeof(ulong)) 883 | { 884 | unchecked 885 | { 886 | il.Emit(OpCodes.Ldc_I8, (long)(ulong)constant); 887 | } 888 | } 889 | else if (constantActualType == typeof(float)) 890 | { 891 | il.Emit(OpCodes.Ldc_R8, (float)constant); 892 | } 893 | else if (constantActualType == typeof(double)) 894 | { 895 | il.Emit(OpCodes.Ldc_R8, (double)constant); 896 | } 897 | else if (constantActualType == typeof(bool)) 898 | { 899 | il.Emit((bool)constant ? OpCodes.Ldc_I4_1 : OpCodes.Ldc_I4_0); 900 | } 901 | else if (constant is string) 902 | { 903 | il.Emit(OpCodes.Ldstr, (string)constant); 904 | } 905 | else if (constant is Type) 906 | { 907 | il.Emit(OpCodes.Ldtoken, (Type)constant); 908 | var getTypeFromHandle = typeof(Type).GetTypeInfo() 909 | .DeclaredMethods.First(m => m.Name == "GetTypeFromHandle"); 910 | il.Emit(OpCodes.Call, getTypeFromHandle); 911 | } 912 | else if (closure != null) 913 | { 914 | var constantIndex = closure.ConstantExpressions.IndexOf(e); 915 | if (constantIndex == -1) 916 | return false; 917 | LoadClosureFieldOrItem(il, closure, constantIndex, e.Type); 918 | 919 | } 920 | else return false; 921 | 922 | // boxing the value type, otherwise we can get a strange result when 0 is treated as Null. 923 | if (e.Type == typeof(object) && constantActualType.GetTypeInfo().IsValueType) 924 | il.Emit(OpCodes.Box, constant.GetType()); // using normal type for Enum instead of underlying type 925 | 926 | return true; 927 | } 928 | 929 | private static void LoadClosureFieldOrItem(ILGenerator il, ClosureInfo closure, int constantIndex, Type constantType) 930 | { 931 | // load closure argument: Closure object or Closure array 932 | il.Emit(OpCodes.Ldarg_0); 933 | 934 | if (!closure.IsArray) 935 | { 936 | // load closure field 937 | il.Emit(OpCodes.Ldfld, closure.Fields[constantIndex]); 938 | return; 939 | } 940 | 941 | // load array field 942 | il.Emit(OpCodes.Ldfld, ArrayClosure.ArrayField); 943 | 944 | // load array item index 945 | EmitLoadConstantInt(il, constantIndex); 946 | 947 | // load item from index 948 | il.Emit(OpCodes.Ldelem_Ref); 949 | 950 | // Cast or unbox the object item depending if it is a class or value type 951 | if (constantType != typeof(object)) 952 | { 953 | if (constantType.GetTypeInfo().IsValueType) 954 | il.Emit(OpCodes.Unbox_Any, constantType); 955 | else 956 | il.Emit(OpCodes.Castclass, constantType); 957 | } 958 | } 959 | 960 | private static bool EmitNew(NewExpression e, IList ps, ILGenerator il, ClosureInfo closure) 961 | { 962 | if (!EmitMany(e.Arguments, ps, il, closure)) 963 | return false; 964 | il.Emit(OpCodes.Newobj, e.Constructor); 965 | return true; 966 | } 967 | 968 | private static bool EmitNewArray(NewArrayExpression e, IList ps, ILGenerator il, ClosureInfo closure) 969 | { 970 | var elems = e.Expressions; 971 | var arrType = e.Type; 972 | var elemType = arrType.GetElementType(); 973 | var isElemOfValueType = elemType.GetTypeInfo().IsValueType; 974 | 975 | var arrVar = il.DeclareLocal(arrType); 976 | 977 | EmitLoadConstantInt(il, elems.Count); 978 | il.Emit(OpCodes.Newarr, elemType); 979 | il.Emit(OpCodes.Stloc, arrVar); 980 | 981 | for (int i = 0, n = elems.Count; i < n; i++) 982 | { 983 | il.Emit(OpCodes.Ldloc, arrVar); 984 | EmitLoadConstantInt(il, i); 985 | 986 | // loading element address for later copying of value into it. 987 | if (isElemOfValueType) 988 | il.Emit(OpCodes.Ldelema, elemType); 989 | 990 | if (!TryEmit(elems[i], ps, il, closure)) 991 | return false; 992 | 993 | if (isElemOfValueType) 994 | il.Emit(OpCodes.Stobj, elemType); // store element of value type by array element address 995 | else 996 | il.Emit(OpCodes.Stelem_Ref); 997 | } 998 | 999 | il.Emit(OpCodes.Ldloc, arrVar); 1000 | return true; 1001 | } 1002 | 1003 | private static bool EmitArrayIndex(BinaryExpression e, IList ps, ILGenerator il, ClosureInfo closure) 1004 | { 1005 | if (!EmitBinary(e, ps, il, closure)) 1006 | return false; 1007 | il.Emit(OpCodes.Ldelem_Ref); 1008 | return true; 1009 | } 1010 | 1011 | private static bool EmitMemberInit(MemberInitExpression mi, IList ps, ILGenerator il, ClosureInfo closure) 1012 | { 1013 | if (!EmitNew(mi.NewExpression, ps, il, closure)) 1014 | return false; 1015 | 1016 | var obj = il.DeclareLocal(mi.Type); 1017 | il.Emit(OpCodes.Stloc, obj); 1018 | 1019 | var bindings = mi.Bindings; 1020 | for (int i = 0, n = bindings.Count; i < n; i++) 1021 | { 1022 | var binding = bindings[i]; 1023 | if (binding.BindingType != MemberBindingType.Assignment) 1024 | return false; 1025 | il.Emit(OpCodes.Ldloc, obj); 1026 | 1027 | if (!TryEmit(((MemberAssignment)binding).Expression, ps, il, closure)) 1028 | return false; 1029 | 1030 | var prop = binding.Member as PropertyInfo; 1031 | if (prop != null) 1032 | { 1033 | var propSetMethodName = "set_" + prop.Name; 1034 | var setMethod = prop.DeclaringType.GetTypeInfo() 1035 | .DeclaredMethods.FirstOrDefault(m => m.Name == propSetMethodName); 1036 | if (setMethod == null) 1037 | return false; 1038 | EmitMethodCall(setMethod, il); 1039 | } 1040 | else 1041 | { 1042 | var field = binding.Member as FieldInfo; 1043 | if (field == null) 1044 | return false; 1045 | il.Emit(OpCodes.Stfld, field); 1046 | } 1047 | } 1048 | 1049 | il.Emit(OpCodes.Ldloc, obj); 1050 | return true; 1051 | } 1052 | 1053 | private static bool EmitMethodCall(MethodCallExpression e, IList ps, ILGenerator il, ClosureInfo closure) 1054 | { 1055 | var methodOwnerExpr = e.Object; 1056 | if (methodOwnerExpr != null) 1057 | { 1058 | if (!TryEmit(methodOwnerExpr, ps, il, closure)) 1059 | return false; 1060 | ForValueTypeStoreAndLoadValueAddress(il, methodOwnerExpr.Type); 1061 | } 1062 | 1063 | if (e.Arguments.Count != 0 && 1064 | !EmitMany(e.Arguments, ps, il, closure)) 1065 | return false; 1066 | 1067 | EmitMethodCall(e.Method, il); 1068 | return true; 1069 | } 1070 | 1071 | private static void ForValueTypeStoreAndLoadValueAddress(ILGenerator il, Type ownerType) 1072 | { 1073 | if (ownerType.GetTypeInfo().IsValueType) 1074 | { 1075 | var valueVar = il.DeclareLocal(ownerType); 1076 | il.Emit(OpCodes.Stloc, valueVar); 1077 | il.Emit(OpCodes.Ldloca, valueVar); 1078 | } 1079 | } 1080 | 1081 | private static bool EmitMemberAccess(MemberExpression e, IList ps, ILGenerator il, ClosureInfo closure) 1082 | { 1083 | var memberOwnerExpr = e.Expression; 1084 | if (memberOwnerExpr != null) 1085 | { 1086 | if (!TryEmit(memberOwnerExpr, ps, il, closure)) 1087 | return false; 1088 | ForValueTypeStoreAndLoadValueAddress(il, memberOwnerExpr.Type); 1089 | } 1090 | 1091 | var field = e.Member as FieldInfo; 1092 | if (field != null) 1093 | { 1094 | il.Emit(field.IsStatic ? OpCodes.Ldsfld : OpCodes.Ldfld, field); 1095 | return true; 1096 | } 1097 | 1098 | var prop = e.Member as PropertyInfo; 1099 | if (prop != null) 1100 | { 1101 | var propGetMethodName = "get_" + prop.Name; 1102 | var getMethod = prop.DeclaringType.GetTypeInfo() 1103 | .DeclaredMethods.FirstOrDefault(_ => _.Name == propGetMethodName); 1104 | if (getMethod == null) 1105 | return false; 1106 | EmitMethodCall(getMethod, il); 1107 | } 1108 | return true; 1109 | } 1110 | 1111 | private static bool EmitNestedLambda(LambdaExpression lambdaExpr, IList paramExprs, ILGenerator il, ClosureInfo closure) 1112 | { 1113 | // First, find in closed compiled lambdas the one corresponding to the current lambda expression. 1114 | var nestedLambdas = closure.NestedLambdas; 1115 | var nestedLambdaIndex = nestedLambdas.Count - 1; 1116 | while (nestedLambdaIndex >= 0 && nestedLambdas[nestedLambdaIndex].LambdaExpr != lambdaExpr) 1117 | --nestedLambdaIndex; 1118 | 1119 | // Situation with not found lambda is not possible/exceptional - 1120 | // means that we somehow skipped the lambda expression while collecting closure info. 1121 | if (nestedLambdaIndex == -1) 1122 | return false; 1123 | 1124 | var nestedLambdaInfo = nestedLambdas[nestedLambdaIndex]; 1125 | var nestedLambda = nestedLambdaInfo.Lambda; 1126 | var nestedLambdaType = nestedLambda.GetType(); 1127 | 1128 | // Next we are loading compiled lambda on stack 1129 | var closureItemIndex = nestedLambdaIndex + closure.ConstantCount + closure.UsedParamCount; 1130 | LoadClosureFieldOrItem(il, closure, closureItemIndex, nestedLambdaType); 1131 | 1132 | // If lambda does not use any outer parameters to be set in closure, then we're done 1133 | var nestedLambdaClosure = nestedLambdaInfo.ClosureInfo; 1134 | if (nestedLambdaClosure == null || 1135 | nestedLambdaClosure.UsedParamExpressions == null) 1136 | return true; 1137 | 1138 | // Sets closure param placeholder fields to the param values 1139 | var nestedLambdaUsedParamExprs = nestedLambdaClosure.UsedParamExpressions; 1140 | for (var i = 0; i < nestedLambdaUsedParamExprs.Count; i++) 1141 | { 1142 | var nestedUsedParamExpr = nestedLambdaUsedParamExprs[i]; 1143 | 1144 | // copy lambda field on stack in order to set it Target.Param to param value 1145 | il.Emit(OpCodes.Dup); 1146 | 1147 | // load lambda.Target property 1148 | EmitMethodCall(_getDelegateTargetProperty, il); 1149 | 1150 | // params go after constants 1151 | var nestedUsedParamIndex = i + nestedLambdaClosure.ConstantCount; 1152 | 1153 | if (nestedLambdaClosure.IsArray) 1154 | { 1155 | // load array field 1156 | il.Emit(OpCodes.Ldfld, ArrayClosure.ArrayField); 1157 | 1158 | // load array item index 1159 | EmitLoadConstantInt(il, nestedUsedParamIndex); 1160 | } 1161 | 1162 | var paramIndex = paramExprs.IndexOf(nestedUsedParamExpr); 1163 | if (paramIndex != -1) // load param from input params 1164 | { 1165 | // +1 is set cause of added first closure argument 1166 | LoadParamArg(il, paramIndex + 1); 1167 | } 1168 | else // load parameter from outer closure 1169 | { 1170 | if (closure.UsedParamExpressions == null) 1171 | return false; // impossible, better to throw? 1172 | 1173 | var outerClosureParamIndex = closure.UsedParamExpressions.IndexOf(nestedUsedParamExpr); 1174 | if (outerClosureParamIndex == -1) 1175 | return false; // impossible, better to throw? 1176 | 1177 | var outerClosureParamItemIndex = closure.ConstantCount + outerClosureParamIndex; 1178 | LoadClosureFieldOrItem(il, closure, outerClosureParamItemIndex, nestedUsedParamExpr.Type); 1179 | } 1180 | 1181 | if (nestedLambdaClosure.IsArray) 1182 | { 1183 | // box value types before setting the object array item 1184 | if (nestedUsedParamExpr.Type.GetTypeInfo().IsValueType) 1185 | il.Emit(OpCodes.Box, nestedUsedParamExpr.Type); 1186 | 1187 | // load item from index 1188 | il.Emit(OpCodes.Stelem_Ref); 1189 | } 1190 | else 1191 | { 1192 | var closedParamField = nestedLambdaClosure.Fields[nestedUsedParamIndex]; 1193 | il.Emit(OpCodes.Stfld, closedParamField); 1194 | } 1195 | } 1196 | 1197 | return true; 1198 | } 1199 | 1200 | private static bool EmitInvokeLambda(InvocationExpression e, IList paramExprs, ILGenerator il, ClosureInfo closure) 1201 | { 1202 | if (!TryEmit(e.Expression, paramExprs, il, closure) || 1203 | !EmitMany(e.Arguments, paramExprs, il, closure)) 1204 | return false; 1205 | 1206 | var invokeMethod = e.Expression.Type.GetTypeInfo().DeclaredMethods.First(m => m.Name == "Invoke"); 1207 | EmitMethodCall(invokeMethod, il); 1208 | return true; 1209 | } 1210 | 1211 | private static bool EmitComparison(BinaryExpression e, IList ps, ILGenerator il, ClosureInfo closure) 1212 | { 1213 | if (!TryEmit(e.Left, ps, il, closure) || 1214 | !TryEmit(e.Right, ps, il, closure)) 1215 | return false; 1216 | 1217 | switch (e.NodeType) 1218 | { 1219 | case ExpressionType.Equal: 1220 | il.Emit(OpCodes.Ceq); 1221 | break; 1222 | case ExpressionType.LessThan: 1223 | il.Emit(OpCodes.Clt); 1224 | break; 1225 | case ExpressionType.GreaterThan: 1226 | il.Emit(OpCodes.Cgt); 1227 | break; 1228 | case ExpressionType.NotEqual: 1229 | il.Emit(OpCodes.Ceq); 1230 | il.Emit(OpCodes.Ldc_I4_0); 1231 | il.Emit(OpCodes.Ceq); 1232 | break; 1233 | case ExpressionType.LessThanOrEqual: 1234 | il.Emit(OpCodes.Cgt); 1235 | il.Emit(OpCodes.Ldc_I4_0); 1236 | il.Emit(OpCodes.Ceq); 1237 | break; 1238 | case ExpressionType.GreaterThanOrEqual: 1239 | il.Emit(OpCodes.Clt); 1240 | il.Emit(OpCodes.Ldc_I4_0); 1241 | il.Emit(OpCodes.Ceq); 1242 | break; 1243 | } 1244 | return true; 1245 | } 1246 | 1247 | private static bool EmitLogicalOperator(BinaryExpression e, IList ps, ILGenerator il, ClosureInfo closure) 1248 | { 1249 | if (!TryEmit(e.Left, ps, il, closure)) 1250 | return false; 1251 | 1252 | var labelSkipRight = il.DefineLabel(); 1253 | var isAnd = e.NodeType == ExpressionType.AndAlso; 1254 | il.Emit(isAnd ? OpCodes.Brfalse_S : OpCodes.Brtrue_S, labelSkipRight); 1255 | 1256 | if (!TryEmit(e.Right, ps, il, closure)) 1257 | return false; 1258 | var labelDone = il.DefineLabel(); 1259 | il.Emit(OpCodes.Br, labelDone); 1260 | 1261 | il.MarkLabel(labelSkipRight); // label the second branch 1262 | il.Emit(isAnd ? OpCodes.Ldc_I4_0 : OpCodes.Ldc_I4_1); 1263 | 1264 | il.MarkLabel(labelDone); 1265 | return true; 1266 | } 1267 | 1268 | private static bool EmitTernararyOperator(ConditionalExpression e, IList ps, ILGenerator il, ClosureInfo closure) 1269 | { 1270 | if (!TryEmit(e.Test, ps, il, closure)) 1271 | return false; 1272 | 1273 | var labelIfFalse = il.DefineLabel(); 1274 | il.Emit(OpCodes.Brfalse_S, labelIfFalse); 1275 | 1276 | if (!TryEmit(e.IfTrue, ps, il, closure)) 1277 | return false; 1278 | 1279 | var labelDone = il.DefineLabel(); 1280 | il.Emit(OpCodes.Br, labelDone); 1281 | 1282 | il.MarkLabel(labelIfFalse); 1283 | if (!TryEmit(e.IfFalse, ps, il, closure)) 1284 | return false; 1285 | 1286 | il.MarkLabel(labelDone); 1287 | return true; 1288 | } 1289 | 1290 | private static void EmitMethodCall(MethodInfo method, ILGenerator il) 1291 | { 1292 | il.Emit(method.IsVirtual ? OpCodes.Callvirt : OpCodes.Call, method); 1293 | } 1294 | 1295 | private static void EmitLoadConstantInt(ILGenerator il, int i) 1296 | { 1297 | switch (i) 1298 | { 1299 | case -1: 1300 | il.Emit(OpCodes.Ldc_I4_M1); 1301 | break; 1302 | case 0: 1303 | il.Emit(OpCodes.Ldc_I4_0); 1304 | break; 1305 | case 1: 1306 | il.Emit(OpCodes.Ldc_I4_1); 1307 | break; 1308 | case 2: 1309 | il.Emit(OpCodes.Ldc_I4_2); 1310 | break; 1311 | case 3: 1312 | il.Emit(OpCodes.Ldc_I4_3); 1313 | break; 1314 | case 4: 1315 | il.Emit(OpCodes.Ldc_I4_4); 1316 | break; 1317 | case 5: 1318 | il.Emit(OpCodes.Ldc_I4_5); 1319 | break; 1320 | case 6: 1321 | il.Emit(OpCodes.Ldc_I4_6); 1322 | break; 1323 | case 7: 1324 | il.Emit(OpCodes.Ldc_I4_7); 1325 | break; 1326 | case 8: 1327 | il.Emit(OpCodes.Ldc_I4_8); 1328 | break; 1329 | default: 1330 | il.Emit(OpCodes.Ldc_I4, i); 1331 | break; 1332 | } 1333 | } 1334 | } 1335 | } 1336 | } 1337 | -------------------------------------------------------------------------------- /AutoCopyLib/FindProperty.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Linq.Expressions; 5 | using System.Reflection; 6 | using System.Text; 7 | using System.Threading.Tasks; 8 | 9 | namespace AutoCopyLib 10 | { 11 | public partial class AutoCopy 12 | { 13 | #region FindProperty 14 | internal static MemberInfo FindProperty(LambdaExpression lambdaExpression) 15 | { 16 | Expression expression = lambdaExpression; 17 | bool flag = false; 18 | while (!flag) 19 | { 20 | ExpressionType nodeType = expression.NodeType; 21 | if (nodeType != ExpressionType.Convert) 22 | { 23 | if (nodeType != ExpressionType.Lambda) 24 | { 25 | if (nodeType != ExpressionType.MemberAccess) 26 | { 27 | flag = true; 28 | } 29 | else 30 | { 31 | MemberExpression memberExpression = (MemberExpression)expression; 32 | if (memberExpression.Expression.NodeType != ExpressionType.Parameter && memberExpression.Expression.NodeType != ExpressionType.Convert) 33 | { 34 | throw new ArgumentException(string.Format("Expression '{0}' must resolve to top-level member and not any child object's properties.", lambdaExpression), "lambdaExpression"); 35 | } 36 | return memberExpression.Member; 37 | } 38 | } 39 | else 40 | { 41 | expression = ((LambdaExpression)expression).Body; 42 | } 43 | } 44 | else 45 | { 46 | expression = ((UnaryExpression)expression).Operand; 47 | } 48 | } 49 | throw new Exception("Custom configuration for members is only supported for top-level individual members on a type."); 50 | } 51 | #endregion 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /AutoCopyLib/LockingConcurrentDictionary.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Concurrent; 3 | 4 | namespace AutoCopyLib 5 | { 6 | internal class LockingConcurrentDictionary 7 | { 8 | private readonly ConcurrentDictionary> _dictionary; 9 | 10 | private readonly Func> _valueFactory; 11 | 12 | public LockingConcurrentDictionary(Func valueFactory) 13 | { 14 | this._dictionary = new ConcurrentDictionary>(); 15 | this._valueFactory = ((TKey key) => new Lazy(() => valueFactory(key))); 16 | } 17 | 18 | public TValue GetOrAdd(TKey key) 19 | { 20 | return this._dictionary.GetOrAdd(key, this._valueFactory).Value; 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /AutoCopyLib/Mono.Reflection.dll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ClockGet/AutoCopy/e16cfe0471cebb0394d96a953de7cd9989167fe5/AutoCopyLib/Mono.Reflection.dll -------------------------------------------------------------------------------- /AutoCopyLib/OldExpressionVisitor.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Collections.ObjectModel; 4 | using System.Linq.Expressions; 5 | 6 | namespace AutoCopyLib 7 | { 8 | #region OldExpressionVisitor 9 | [Obsolete("使用System.Core库的System.Linq.Expressions.ExpressionVisitor类")] 10 | public abstract class OldExpressionVisitor 11 | { 12 | protected OldExpressionVisitor() 13 | { 14 | } 15 | 16 | protected virtual Expression Visit(Expression exp) 17 | { 18 | if (exp == null) 19 | return exp; 20 | switch (exp.NodeType) 21 | { 22 | case ExpressionType.Negate: 23 | case ExpressionType.NegateChecked: 24 | case ExpressionType.Not: 25 | case ExpressionType.Convert: 26 | case ExpressionType.ConvertChecked: 27 | case ExpressionType.ArrayLength: 28 | case ExpressionType.Quote: 29 | case ExpressionType.TypeAs: 30 | return this.VisitUnary((UnaryExpression)exp); 31 | case ExpressionType.Add: 32 | case ExpressionType.AddChecked: 33 | case ExpressionType.Subtract: 34 | case ExpressionType.SubtractChecked: 35 | case ExpressionType.Multiply: 36 | case ExpressionType.MultiplyChecked: 37 | case ExpressionType.Divide: 38 | case ExpressionType.Modulo: 39 | case ExpressionType.And: 40 | case ExpressionType.AndAlso: 41 | case ExpressionType.Or: 42 | case ExpressionType.OrElse: 43 | case ExpressionType.LessThan: 44 | case ExpressionType.LessThanOrEqual: 45 | case ExpressionType.GreaterThan: 46 | case ExpressionType.GreaterThanOrEqual: 47 | case ExpressionType.Equal: 48 | case ExpressionType.NotEqual: 49 | case ExpressionType.Coalesce: 50 | case ExpressionType.ArrayIndex: 51 | case ExpressionType.RightShift: 52 | case ExpressionType.LeftShift: 53 | case ExpressionType.ExclusiveOr: 54 | return this.VisitBinary((BinaryExpression)exp); 55 | case ExpressionType.TypeIs: 56 | return this.VisitTypeIs((TypeBinaryExpression)exp); 57 | case ExpressionType.Conditional: 58 | return this.VisitConditional((ConditionalExpression)exp); 59 | case ExpressionType.Constant: 60 | return this.VisitConstant((ConstantExpression)exp); 61 | case ExpressionType.Parameter: 62 | return this.VisitParameter((ParameterExpression)exp); 63 | case ExpressionType.MemberAccess: 64 | return this.VisitMemberAccess((MemberExpression)exp); 65 | case ExpressionType.Call: 66 | return this.VisitMethodCall((MethodCallExpression)exp); 67 | case ExpressionType.Lambda: 68 | return this.VisitLambda((LambdaExpression)exp); 69 | case ExpressionType.New: 70 | return this.VisitNew((NewExpression)exp); 71 | case ExpressionType.NewArrayInit: 72 | case ExpressionType.NewArrayBounds: 73 | return this.VisitNewArray((NewArrayExpression)exp); 74 | case ExpressionType.Invoke: 75 | return this.VisitInvocation((InvocationExpression)exp); 76 | case ExpressionType.MemberInit: 77 | return this.VisitMemberInit((MemberInitExpression)exp); 78 | case ExpressionType.ListInit: 79 | return this.VisitListInit((ListInitExpression)exp); 80 | default: 81 | throw new Exception(string.Format("Unhandled expression type: '{0}'", exp.NodeType)); 82 | } 83 | } 84 | 85 | protected virtual MemberBinding VisitBinding(MemberBinding binding) 86 | { 87 | switch (binding.BindingType) 88 | { 89 | case MemberBindingType.Assignment: 90 | return this.VisitMemberAssignment((MemberAssignment)binding); 91 | case MemberBindingType.MemberBinding: 92 | return this.VisitMemberMemberBinding((MemberMemberBinding)binding); 93 | case MemberBindingType.ListBinding: 94 | return this.VisitMemberListBinding((MemberListBinding)binding); 95 | default: 96 | throw new Exception(string.Format("Unhandled binding type '{0}'", binding.BindingType)); 97 | } 98 | } 99 | 100 | protected virtual ElementInit VisitElementInitializer(ElementInit initializer) 101 | { 102 | ReadOnlyCollection arguments = this.VisitExpressionList(initializer.Arguments); 103 | if (arguments != initializer.Arguments) 104 | { 105 | return Expression.ElementInit(initializer.AddMethod, arguments); 106 | } 107 | return initializer; 108 | } 109 | 110 | protected virtual Expression VisitUnary(UnaryExpression u) 111 | { 112 | Expression operand = this.Visit(u.Operand); 113 | if (operand != u.Operand) 114 | { 115 | return Expression.MakeUnary(u.NodeType, operand, u.Type, u.Method); 116 | } 117 | return u; 118 | } 119 | 120 | protected virtual Expression VisitBinary(BinaryExpression b) 121 | { 122 | Expression left = this.Visit(b.Left); 123 | Expression right = this.Visit(b.Right); 124 | Expression conversion = this.Visit(b.Conversion); 125 | if (left != b.Left || right != b.Right || conversion != b.Conversion) 126 | { 127 | if (b.NodeType == ExpressionType.Coalesce && b.Conversion != null) 128 | return Expression.Coalesce(left, right, conversion as LambdaExpression); 129 | else 130 | return Expression.MakeBinary(b.NodeType, left, right, b.IsLiftedToNull, b.Method); 131 | } 132 | return b; 133 | } 134 | 135 | protected virtual Expression VisitTypeIs(TypeBinaryExpression b) 136 | { 137 | Expression expr = this.Visit(b.Expression); 138 | if (expr != b.Expression) 139 | { 140 | return Expression.TypeIs(expr, b.TypeOperand); 141 | } 142 | return b; 143 | } 144 | 145 | protected virtual Expression VisitConstant(ConstantExpression c) 146 | { 147 | return c; 148 | } 149 | 150 | protected virtual Expression VisitConditional(ConditionalExpression c) 151 | { 152 | Expression test = this.Visit(c.Test); 153 | Expression ifTrue = this.Visit(c.IfTrue); 154 | Expression ifFalse = this.Visit(c.IfFalse); 155 | if (test != c.Test || ifTrue != c.IfTrue || ifFalse != c.IfFalse) 156 | { 157 | return Expression.Condition(test, ifTrue, ifFalse); 158 | } 159 | return c; 160 | } 161 | 162 | protected virtual Expression VisitParameter(ParameterExpression p) 163 | { 164 | return p; 165 | } 166 | 167 | protected virtual Expression VisitMemberAccess(MemberExpression m) 168 | { 169 | Expression exp = this.Visit(m.Expression); 170 | if (exp != m.Expression) 171 | { 172 | return Expression.MakeMemberAccess(exp, m.Member); 173 | } 174 | return m; 175 | } 176 | 177 | protected virtual Expression VisitMethodCall(MethodCallExpression m) 178 | { 179 | Expression obj = this.Visit(m.Object); 180 | IEnumerable args = this.VisitExpressionList(m.Arguments); 181 | if (obj != m.Object || args != m.Arguments) 182 | { 183 | return Expression.Call(obj, m.Method, args); 184 | } 185 | return m; 186 | } 187 | 188 | protected virtual ReadOnlyCollection VisitExpressionList(ReadOnlyCollection original) 189 | { 190 | List list = null; 191 | for (int i = 0, n = original.Count; i < n; i++) 192 | { 193 | Expression p = this.Visit(original[i]); 194 | if (list != null) 195 | { 196 | list.Add(p); 197 | } 198 | else if (p != original[i]) 199 | { 200 | list = new List(n); 201 | for (int j = 0; j < i; j++) 202 | { 203 | list.Add(original[j]); 204 | } 205 | list.Add(p); 206 | } 207 | } 208 | if (list != null) 209 | { 210 | return list.AsReadOnly(); 211 | } 212 | return original; 213 | } 214 | 215 | protected virtual MemberAssignment VisitMemberAssignment(MemberAssignment assignment) 216 | { 217 | Expression e = this.Visit(assignment.Expression); 218 | if (e != assignment.Expression) 219 | { 220 | return Expression.Bind(assignment.Member, e); 221 | } 222 | return assignment; 223 | } 224 | 225 | protected virtual MemberMemberBinding VisitMemberMemberBinding(MemberMemberBinding binding) 226 | { 227 | IEnumerable bindings = this.VisitBindingList(binding.Bindings); 228 | if (bindings != binding.Bindings) 229 | { 230 | return Expression.MemberBind(binding.Member, bindings); 231 | } 232 | return binding; 233 | } 234 | 235 | protected virtual MemberListBinding VisitMemberListBinding(MemberListBinding binding) 236 | { 237 | IEnumerable initializers = this.VisitElementInitializerList(binding.Initializers); 238 | if (initializers != binding.Initializers) 239 | { 240 | return Expression.ListBind(binding.Member, initializers); 241 | } 242 | return binding; 243 | } 244 | 245 | protected virtual IEnumerable VisitBindingList(ReadOnlyCollection original) 246 | { 247 | List list = null; 248 | for (int i = 0, n = original.Count; i < n; i++) 249 | { 250 | MemberBinding b = this.VisitBinding(original[i]); 251 | if (list != null) 252 | { 253 | list.Add(b); 254 | } 255 | else if (b != original[i]) 256 | { 257 | list = new List(n); 258 | for (int j = 0; j < i; j++) 259 | { 260 | list.Add(original[j]); 261 | } 262 | list.Add(b); 263 | } 264 | } 265 | if (list != null) 266 | return list; 267 | return original; 268 | } 269 | 270 | protected virtual IEnumerable VisitElementInitializerList(ReadOnlyCollection original) 271 | { 272 | List list = null; 273 | for (int i = 0, n = original.Count; i < n; i++) 274 | { 275 | ElementInit init = this.VisitElementInitializer(original[i]); 276 | if (list != null) 277 | { 278 | list.Add(init); 279 | } 280 | else if (init != original[i]) 281 | { 282 | list = new List(n); 283 | for (int j = 0; j < i; j++) 284 | { 285 | list.Add(original[j]); 286 | } 287 | list.Add(init); 288 | } 289 | } 290 | if (list != null) 291 | return list; 292 | return original; 293 | } 294 | 295 | protected virtual Expression VisitLambda(LambdaExpression lambda) 296 | { 297 | Expression body = this.Visit(lambda.Body); 298 | if (body != lambda.Body) 299 | { 300 | return Expression.Lambda(lambda.Type, body, lambda.Parameters); 301 | } 302 | return lambda; 303 | } 304 | 305 | protected virtual NewExpression VisitNew(NewExpression nex) 306 | { 307 | IEnumerable args = this.VisitExpressionList(nex.Arguments); 308 | if (args != nex.Arguments) 309 | { 310 | if (nex.Members != null) 311 | return Expression.New(nex.Constructor, args, nex.Members); 312 | else 313 | return Expression.New(nex.Constructor, args); 314 | } 315 | return nex; 316 | } 317 | 318 | protected virtual Expression VisitMemberInit(MemberInitExpression init) 319 | { 320 | NewExpression n = this.VisitNew(init.NewExpression); 321 | IEnumerable bindings = this.VisitBindingList(init.Bindings); 322 | if (n != init.NewExpression || bindings != init.Bindings) 323 | { 324 | return Expression.MemberInit(n, bindings); 325 | } 326 | return init; 327 | } 328 | 329 | protected virtual Expression VisitListInit(ListInitExpression init) 330 | { 331 | NewExpression n = this.VisitNew(init.NewExpression); 332 | IEnumerable initializers = this.VisitElementInitializerList(init.Initializers); 333 | if (n != init.NewExpression || initializers != init.Initializers) 334 | { 335 | return Expression.ListInit(n, initializers); 336 | } 337 | return init; 338 | } 339 | 340 | protected virtual Expression VisitNewArray(NewArrayExpression na) 341 | { 342 | IEnumerable exprs = this.VisitExpressionList(na.Expressions); 343 | if (exprs != na.Expressions) 344 | { 345 | if (na.NodeType == ExpressionType.NewArrayInit) 346 | { 347 | return Expression.NewArrayInit(na.Type.GetElementType(), exprs); 348 | } 349 | else 350 | { 351 | return Expression.NewArrayBounds(na.Type.GetElementType(), exprs); 352 | } 353 | } 354 | return na; 355 | } 356 | 357 | protected virtual Expression VisitInvocation(InvocationExpression iv) 358 | { 359 | IEnumerable args = this.VisitExpressionList(iv.Arguments); 360 | Expression expr = this.Visit(iv.Expression); 361 | if (args != iv.Arguments || expr != iv.Expression) 362 | { 363 | return Expression.Invoke(expr, args); 364 | } 365 | return iv; 366 | } 367 | } 368 | #endregion 369 | } 370 | -------------------------------------------------------------------------------- /AutoCopyLib/Option.cs: -------------------------------------------------------------------------------- 1 | using AutoCopyLib.Visitors; 2 | using System; 3 | using System.Linq; 4 | using System.Linq.Expressions; 5 | using System.Reflection; 6 | 7 | namespace AutoCopyLib 8 | { 9 | public partial class AutoCopy 10 | { 11 | public class Option

: ExpressionVisitor 12 | { 13 | protected override Expression VisitParameter(ParameterExpression p)//替换掉对象 14 | { 15 | if (p.Name == "name" && p.Type == typeof(string)) 16 | return p; 17 | if (p.Type == typeof(P)) 18 | return _parameterTuple.Source; 19 | return p; 20 | } 21 | protected override Expression VisitMethodCall(MethodCallExpression node) 22 | { 23 | //判断调用方法的实例是否为AutoCopy<>的派生类 24 | if (node.Object != null && IsAssignableToGenericType(node.Object.Type, typeof(AutoCopy<,>))) 25 | { 26 | //获取调用方法的实例 27 | var member = (MemberExpression)node.Object; 28 | var argument = Visit(node.Arguments[0]); 29 | var constant = (ConstantExpression)member.Expression; 30 | var anonymousClassInstance = constant.Value; 31 | var calledClassField = (FieldInfo)member.Member; 32 | var calledClass = calledClassField.GetValue(anonymousClassInstance); 33 | //调用实例的RegisterCore方法,获取Lambda表达式 34 | var autoCopyType = calledClass.GetType(); 35 | object lambda = autoCopyType.InvokeMember("Decompiler", BindingFlags.Instance | BindingFlags.Public | BindingFlags.InvokeMethod, null, calledClass, new object[] { false }); 36 | LambdaExpression lambdaExpression = (LambdaExpression)lambda; 37 | return Expression.Invoke(lambdaExpression, argument, _parameterTuple.ErrorMsg); 38 | } 39 | return base.VisitMethodCall(node); 40 | } 41 | private ParameterTuple _parameterTuple; 42 | public Option(ParameterTuple parameterTuple) 43 | { 44 | _parameterTuple = parameterTuple; 45 | } 46 | public Expression MapFrom( 47 | Expression> selector) 48 | { 49 | Expression body = selector; 50 | if (body is LambdaExpression) 51 | { 52 | body = ((LambdaExpression)body).Body; 53 | } 54 | var body2 = Visit(body); 55 | return body2; 56 | } 57 | public Expression MapFrom(Expression> selector) 58 | { 59 | Expression body = selector; 60 | if (body is LambdaExpression) 61 | { 62 | body = ((LambdaExpression)body).Body; 63 | } 64 | var body2 = Visit(body); 65 | return body2; 66 | } 67 | public Func ResolveUsing(Func resolver) 68 | { 69 | return resolver; 70 | } 71 | bool IsAssignableToGenericType(Type givenType, Type genericType) 72 | { 73 | var interfaceTypes = givenType.GetInterfaces(); 74 | 75 | foreach (var it in interfaceTypes) 76 | { 77 | if (it.IsGenericType && it.GetGenericTypeDefinition() == genericType) 78 | return true; 79 | } 80 | 81 | if (givenType.IsGenericType && givenType.GetGenericTypeDefinition() == genericType) 82 | return true; 83 | 84 | Type baseType = givenType.BaseType; 85 | if (baseType == null) return false; 86 | 87 | return IsAssignableToGenericType(baseType, genericType); 88 | } 89 | } 90 | } 91 | } 92 | -------------------------------------------------------------------------------- /AutoCopyLib/ParameterTuple.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Linq.Expressions; 3 | 4 | namespace AutoCopyLib 5 | { 6 | public partial class AutoCopy 7 | { 8 | public class ParameterTuple 9 | { 10 | public ParameterTuple(ParameterExpression p1, ParameterExpression p2, ParameterExpression p3) 11 | { 12 | Destination = p1; 13 | Source = p2; 14 | ErrorMsg = p3; 15 | } 16 | public ParameterExpression Destination { get; } 17 | public ParameterExpression Source { get; } 18 | public ParameterExpression ErrorMsg { get; } 19 | public IEnumerable Collect() 20 | { 21 | yield return Destination; 22 | yield return Source; 23 | yield return ErrorMsg; 24 | } 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /AutoCopyLib/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // 有关程序集的一般信息由以下 6 | // 控制。更改这些特性值可修改 7 | // 与程序集关联的信息。 8 | [assembly: AssemblyTitle("AutoCopyLib")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("")] 12 | [assembly: AssemblyProduct("AutoCopyLib")] 13 | [assembly: AssemblyCopyright("Copyright © 2017")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | //将 ComVisible 设置为 false 将使此程序集中的类型 18 | //对 COM 组件不可见。 如果需要从 COM 访问此程序集中的类型, 19 | //请将此类型的 ComVisible 特性设置为 true。 20 | [assembly: ComVisible(false)] 21 | 22 | // 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID 23 | [assembly: Guid("c2685dab-9618-4fdc-8e85-248e1069ac39")] 24 | 25 | // 程序集的版本信息由下列四个值组成: 26 | // 27 | // 主版本 28 | // 次版本 29 | // 生成号 30 | // 修订号 31 | // 32 | //可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值, 33 | // 方法是按如下所示使用“*”: : 34 | // [assembly: AssemblyVersion("1.0.*")] 35 | [assembly: AssemblyVersion("1.0.0.0")] 36 | [assembly: AssemblyFileVersion("1.0.0.0")] 37 | -------------------------------------------------------------------------------- /AutoCopyLib/ReflectExt.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Reflection; 5 | using System.Reflection.Emit; 6 | using System.Text; 7 | 8 | namespace AutoCopyLib 9 | { 10 | public static class ReflectExt 11 | { 12 | public static OpCode[] GetOpCodes(byte[] data) 13 | { 14 | var opCodes = typeof(OpCodes) 15 | .GetFields() 16 | .Select(fi => (OpCode)fi.GetValue(null)); 17 | return data.Select(op => 18 | opCodes.FirstOrDefault(opCode => opCode.Value == op)).Where(p=>p!=null).ToArray(); 19 | } 20 | public static string DumpMethod(Delegate method) 21 | { 22 | // For aggregating our response 23 | StringBuilder sb = new StringBuilder(); 24 | 25 | // First we need to extract out the raw IL 26 | var mb = method.Method.GetMethodBody(); 27 | var il = mb.GetILAsByteArray(); 28 | 29 | // We'll also need a full set of the IL opcodes so we 30 | // can remap them over our method body 31 | var opCodes = typeof(System.Reflection.Emit.OpCodes) 32 | .GetFields() 33 | .Select(fi => (System.Reflection.Emit.OpCode)fi.GetValue(null)); 34 | 35 | //opCodes.Dump(); 36 | 37 | // For each byte in our method body, try to match it to an opcode 38 | var mappedIL = il.Select(op => 39 | opCodes.FirstOrDefault(opCode => opCode.Value == op)); 40 | 41 | // OpCode/Operand parsing: 42 | // Some opcodes have no operands, some use ints, etc. 43 | // let's try to cover all cases 44 | var ilWalker = mappedIL.GetEnumerator(); 45 | while (ilWalker.MoveNext()) 46 | { 47 | var mappedOp = ilWalker.Current; 48 | if (mappedOp.OperandType != OperandType.InlineNone) 49 | { 50 | // For operand inference: 51 | // MOST operands are 32 bit, 52 | // so we'll start there 53 | var byteCount = 4; 54 | long operand = 0; 55 | string token = string.Empty; 56 | 57 | // For metadata token resolution 58 | var module = method.Method.Module; 59 | Func tokenResolver = tkn => string.Empty; 60 | switch (mappedOp.OperandType) 61 | { 62 | // These are all 32bit metadata tokens 63 | case OperandType.InlineMethod: 64 | tokenResolver = tkn => 65 | { 66 | var resMethod = module.SafeResolveMethod((int)tkn); 67 | return string.Format("({0}())", resMethod == null ? "unknown" : resMethod.Name); 68 | }; 69 | break; 70 | case OperandType.InlineField: 71 | tokenResolver = tkn => 72 | { 73 | var field = module.SafeResolveField((int)tkn); 74 | return string.Format("({0})", field == null ? "unknown" : field.Name); 75 | }; 76 | break; 77 | case OperandType.InlineSig: 78 | tokenResolver = tkn => 79 | { 80 | var sigBytes = module.SafeResolveSignature((int)tkn); 81 | var catSig = string 82 | .Join(",", sigBytes); 83 | return string.Format("(SIG:{0})", catSig == null ? "unknown" : catSig); 84 | }; 85 | break; 86 | case OperandType.InlineString: 87 | tokenResolver = tkn => 88 | { 89 | var str = module.SafeResolveString((int)tkn); 90 | return string.Format("('{0}')", str == null ? "unknown" : str); 91 | }; 92 | break; 93 | case OperandType.InlineType: 94 | tokenResolver = tkn => 95 | { 96 | var type = module.SafeResolveType((int)tkn); 97 | return string.Format("(typeof({0}))", type == null ? "unknown" : type.Name); 98 | }; 99 | break; 100 | // These are plain old 32bit operands 101 | case OperandType.InlineI: 102 | case OperandType.InlineBrTarget: 103 | case OperandType.InlineSwitch: 104 | case OperandType.ShortInlineR: 105 | break; 106 | // These are 64bit operands 107 | case OperandType.InlineI8: 108 | case OperandType.InlineR: 109 | byteCount = 8; 110 | break; 111 | // These are all 8bit values 112 | case OperandType.ShortInlineBrTarget: 113 | case OperandType.ShortInlineI: 114 | case OperandType.ShortInlineVar: 115 | byteCount = 1; 116 | break; 117 | } 118 | // Based on byte count, pull out the full operand 119 | for (int i = 0; i < byteCount; i++) 120 | { 121 | ilWalker.MoveNext(); 122 | operand |= ((long)ilWalker.Current.Value) << (8 * i); 123 | } 124 | 125 | var resolved = tokenResolver((int)operand); 126 | resolved = string.IsNullOrEmpty(resolved) ? operand.ToString() : resolved; 127 | sb.AppendFormat("{0} {1}", 128 | mappedOp.Name, 129 | resolved) 130 | .AppendLine(); 131 | } 132 | else 133 | { 134 | sb.AppendLine(mappedOp.Name); 135 | } 136 | } 137 | return sb.ToString(); 138 | } 139 | public static FieldInfo SafeResolveField(this Module m, int token) 140 | { 141 | FieldInfo fi; 142 | m.TryResolveField(token, out fi); 143 | return fi; 144 | } 145 | public static bool TryResolveField(this Module m, int token, out FieldInfo fi) 146 | { 147 | var ok = false; 148 | try { fi = m.ResolveField(token); ok = true; } 149 | catch { fi = null; } 150 | return ok; 151 | } 152 | public static MethodBase SafeResolveMethod(this Module m, int token) 153 | { 154 | MethodBase fi; 155 | m.TryResolveMethod(token, out fi); 156 | return fi; 157 | } 158 | public static bool TryResolveMethod(this Module m, int token, out MethodBase fi) 159 | { 160 | var ok = false; 161 | try { fi = m.ResolveMethod(token); ok = true; } 162 | catch { fi = null; } 163 | return ok; 164 | } 165 | public static string SafeResolveString(this Module m, int token) 166 | { 167 | string fi; 168 | m.TryResolveString(token, out fi); 169 | return fi; 170 | } 171 | public static bool TryResolveString(this Module m, int token, out string fi) 172 | { 173 | var ok = false; 174 | try { fi = m.ResolveString(token); ok = true; } 175 | catch { fi = null; } 176 | return ok; 177 | } 178 | public static byte[] SafeResolveSignature(this Module m, int token) 179 | { 180 | byte[] fi; 181 | m.TryResolveSignature(token, out fi); 182 | return fi; 183 | } 184 | public static bool TryResolveSignature(this Module m, int token, out byte[] fi) 185 | { 186 | var ok = false; 187 | try { fi = m.ResolveSignature(token); ok = true; } 188 | catch { fi = null; } 189 | return ok; 190 | } 191 | public static Type SafeResolveType(this Module m, int token) 192 | { 193 | Type fi; 194 | m.TryResolveType(token, out fi); 195 | return fi; 196 | } 197 | public static bool TryResolveType(this Module m, int token, out Type fi) 198 | { 199 | var ok = false; 200 | try { fi = m.ResolveType(token); ok = true; } 201 | catch { fi = null; } 202 | return ok; 203 | } 204 | } 205 | } 206 | -------------------------------------------------------------------------------- /AutoCopyLib/Reorganization.cs: -------------------------------------------------------------------------------- 1 | using AutoCopyLib.Visitors; 2 | using System.Linq; 3 | using System.Linq.Expressions; 4 | 5 | namespace AutoCopyLib 6 | { 7 | public partial class AutoCopy 8 | { 9 | public LambdaExpression Decompiler(bool enableNullSafe) 10 | { 11 | LambdaExpression lambdaExpression = this.RegisterCore(enableNullSafe); 12 | var newparameter1 = Expression.Variable(parameterTuple.Destination.Type, parameterTuple.Destination.Name); 13 | var newparameter2 = Expression.Parameter(parameterTuple.Source.Type, parameterTuple.Source.Name); 14 | var newparameter3 = Expression.Parameter(parameterTuple.ErrorMsg.Type.MakeByRefType(), parameterTuple.ErrorMsg.Name); 15 | ParameterTuple newParameterTuple = new ParameterTuple(newparameter1, newparameter2, newparameter3); 16 | var body = this.Body; 17 | var newBody= ParameterReplacer.Replace(body, parameterTuple.Collect().ToArray(), newParameterTuple.Collect().ToArray()) as BlockExpression; 18 | ReturnTargetRewriter returnTargetRewriter = null; 19 | if (hasReturnLabel) 20 | { 21 | returnTargetRewriter = new ReturnTargetRewriter(parameterTuple.Destination.Type, Expression.Default(parameterTuple.Destination.Type)); 22 | newBody = returnTargetRewriter.Visit(newBody) as BlockExpression; 23 | } 24 | //初始化临时变量并构造新的lambda表达式 25 | //去掉原来lambda表达式最后的return true 26 | var initExpression = Expression.Assign(newparameter1, Expression.New(newparameter1.Type)); 27 | Expression returnExpression = null; 28 | int exprCount = newBody.Expressions.Count - 1; 29 | if (hasReturnLabel) 30 | { 31 | returnExpression = Expression.Label(returnTargetRewriter.LabelTarget, returnTargetRewriter.DefaultValue); 32 | ++exprCount; 33 | } 34 | else 35 | returnExpression = newparameter1; 36 | var newBlockExpression = Expression.Block(new[] { newparameter1 }.Concat(newBody.Variables), new[] { initExpression }.Concat(newBody.Expressions.Take(exprCount)).Concat(new[] { returnExpression })); 37 | return Expression.Lambda(newBlockExpression, newParameterTuple.Source, newParameterTuple.ErrorMsg); 38 | } 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /AutoCopyLib/TargetExpressionProviderBase.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Linq.Expressions; 3 | 4 | namespace AutoCopyLib 5 | { 6 | public abstract class TargetExpressionProviderBase 7 | { 8 | public TargetExpressionProviderBase(Type targetType) 9 | { 10 | this._target = targetType; 11 | } 12 | private Type _target; 13 | protected Type Target 14 | { 15 | get 16 | { 17 | return _target; 18 | } 19 | } 20 | public abstract bool TryGetExpression(string name, ParameterExpression parameter, Type destType, out Expression exp, out ParameterExpression variable, out Expression test, out bool ifTrue); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /AutoCopyLib/TypeConverter.cs: -------------------------------------------------------------------------------- 1 | using AutoCopyLib.Utilities; 2 | using System; 3 | using System.Collections.Concurrent; 4 | using System.Collections.Generic; 5 | using System.Linq.Expressions; 6 | using System.Reflection; 7 | 8 | namespace AutoCopyLib 9 | { 10 | internal class TypeConverter 11 | { 12 | private static MethodInfo ChangeTypeMethod = null; 13 | private static ConcurrentDictionary _tryParseDic = new ConcurrentDictionary(); 14 | private static ConcurrentDictionary _toStringDic = new ConcurrentDictionary(); 15 | static TypeConverter() 16 | { 17 | ChangeTypeMethod = typeof(Convert).GetMethod("ChangeType", BindingFlags.Static | BindingFlags.Public, null, new Type[] { typeof(object), typeof(TypeCode) }, new ParameterModifier[0]); 18 | } 19 | public static bool TryConvert(Expression parameter, Type sourceType, Type destType, out Action, ParameterExpression, PropertyInfo, Func> act, out ParameterExpression variable) 20 | { 21 | Expression expression = null; 22 | variable = null; 23 | act = null; 24 | var typeCode = Type.GetTypeCode(sourceType); 25 | if (typeCode == TypeCode.Empty || typeCode == TypeCode.DBNull) 26 | return false; 27 | MethodInfo method = null; 28 | //判断是否可以显式转换 29 | if (destType.GetMethod("op_Explicit",new Type[] {sourceType })!=null) 30 | { 31 | expression = Expression.Convert(parameter, destType); 32 | 33 | } 34 | //判断是否可以隐式转换 35 | else if(destType.GetMethod("op_Implicit", new Type[] { sourceType }) != null) 36 | { 37 | expression = parameter; 38 | } 39 | //判断是否存在继承关系 40 | //Base base=Derive 41 | else if(destType.IsAssignableFrom(sourceType)) 42 | { 43 | expression = parameter; 44 | } 45 | //判断是否存在Convert.ToXX方法 46 | else if (typeCode != TypeCode.String && typeCode != TypeCode.Object && Type.GetTypeCode(destType)!=TypeCode.Object) 47 | { 48 | method = typeof(Convert).GetMethod("To" + destType.Name, BindingFlags.Static | BindingFlags.Public, null, new Type[] { sourceType }, new ParameterModifier[0]); 49 | if (method != null) 50 | { 51 | expression = Expression.Call(null, method, parameter); 52 | } 53 | } 54 | if (expression!=null) 55 | { 56 | act = (list, p1, srcPropertyInfo, func) => 57 | { 58 | list.Add(Expression.Assign(Expression.MakeMemberAccess(p1, srcPropertyInfo), func == null ? expression : func(expression))); 59 | }; 60 | return true; 61 | } 62 | bool skipChangeType = false; 63 | // 目标类型是否存在TryParse方法————————否——————————ChangeType 64 | // | | 65 | // |是 | 66 | // | 否 否 | 67 | // 源类型是否为string———————————是否存在ToString方法————— 68 | // | | 69 | // |是 |是 70 | // |—————————————————————— 71 | // | 72 | // | 73 | // 调用目标类型上的TryParse方法 74 | if ((method = _tryParseDic.GetOrAdd(destType, t => t.GetMethod("TryParse", BindingFlags.Static | BindingFlags.Public, null, new Type[] { typeof(string), t.MakeByRefType() }, new ParameterModifier[0]))) != null) 75 | { 76 | skipChangeType = true; 77 | MethodInfo toStringMethod = null; 78 | //首先判断sourceType是不是string 79 | var r = typeCode != TypeCode.String; 80 | if (r) 81 | { 82 | //如果类型不是string,就需要看该类是否定义了自己的ToString方法 83 | //BindingFlags.DeclaredOnly 标识只获取该类定义的方法,屏蔽继承的方法 84 | if ((toStringMethod = _toStringDic.GetOrAdd(sourceType, t => t.GetMethod("ToString", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly, null, Type.EmptyTypes, new ParameterModifier[0]))) == null) 85 | { 86 | skipChangeType = false; 87 | } 88 | } 89 | if (skipChangeType) 90 | { 91 | Expression temp = parameter; 92 | //如果sourceType不是string 93 | if (r) 94 | { 95 | temp = Expression.Call(parameter, toStringMethod); 96 | } 97 | ParameterExpression p = VariableGenerator.Generate(destType); 98 | expression = Expression.Call(null, method, temp, p); 99 | act = (list, p1, srcPropertyInfo, func) => 100 | { 101 | expression = Expression.IfThen(expression, Expression.Assign(Expression.MakeMemberAccess(p1, srcPropertyInfo), p)); 102 | list.Add(expression); 103 | }; 104 | variable = p; 105 | } 106 | } 107 | if (!skipChangeType) 108 | { 109 | expression = Expression.Convert(Expression.Call(null, ChangeTypeMethod, Expression.Convert(parameter, typeof(object)), Expression.Constant(Type.GetTypeCode(destType), typeof(TypeCode))), destType); 110 | act = (list, p1, srcPropertyInfo, func) => 111 | { 112 | list.Add(Expression.Assign(Expression.MakeMemberAccess(p1, srcPropertyInfo), func == null ? expression : func(expression))); 113 | }; 114 | } 115 | return true; 116 | } 117 | } 118 | } 119 | -------------------------------------------------------------------------------- /AutoCopyLib/TypeTuple.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace AutoCopyLib 4 | { 5 | public class TypeTuple : Tuple 6 | { 7 | public TypeTuple(Type item1, Type item2) : base(item1, item2) 8 | { 9 | } 10 | public override int GetHashCode() 11 | { 12 | return Item1.GetHashCode() + Item2.GetHashCode(); 13 | } 14 | public override bool Equals(object obj) 15 | { 16 | TypeTuple type = obj as TypeTuple; 17 | if (type == null) 18 | return false; 19 | return Item1 == type.Item1 && Item2 == type.Item2; 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /AutoCopyLib/Utilities/Guard.cs: -------------------------------------------------------------------------------- 1 | // Original C# code written by 2 | // Unity - https://github.com/unitycontainer/unity 3 | // Copyright (C) 2015-2017 Microsoft 4 | // 5 | // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this product except in 6 | // compliance with the License. You may obtain a copy of the License at 7 | // 8 | // http://www.apache.org/licenses/LICENSE-2.0 9 | // 10 | // Unless required by applicable law or agreed to in writing, software distributed under the License is 11 | // distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and limitations under the License. 13 | // 14 | 15 | using System; 16 | using System.Reflection; 17 | 18 | namespace AutoCopyLib.Utilities 19 | { 20 | internal static class Guard 21 | { 22 | public static void ArgumentNotNull(object argumentValue, string argumentName) 23 | { 24 | if (argumentValue != null) 25 | { 26 | return; 27 | } 28 | throw new ArgumentNullException(argumentName); 29 | } 30 | 31 | public static void ArgumentNotNullOrEmpty(string argumentValue, string argumentName) 32 | { 33 | if (argumentValue == null) 34 | { 35 | throw new ArgumentNullException(argumentName); 36 | } 37 | if (argumentValue.Length != 0) 38 | { 39 | return; 40 | } 41 | throw new ArgumentException("The provided string argument must not be empty.", argumentName); 42 | } 43 | 44 | public static void TypeIsAssignable(Type assignmentTargetType, Type assignmentValueType, string argumentName) 45 | { 46 | if (assignmentTargetType == (Type)null) 47 | { 48 | throw new ArgumentNullException("assignmentTargetType"); 49 | } 50 | if (assignmentValueType == (Type)null) 51 | { 52 | throw new ArgumentNullException("assignmentValueType"); 53 | } 54 | if (assignmentTargetType.GetTypeInfo().IsAssignableFrom(assignmentValueType.GetTypeInfo())) 55 | { 56 | return; 57 | } 58 | throw new ArgumentException(string.Format("The type {1} cannot be assigned to variables of type {0}.", new object[2] 59 | { 60 | assignmentTargetType, 61 | assignmentValueType 62 | }), argumentName); 63 | } 64 | 65 | public static void InstanceIsAssignable(Type assignmentTargetType, object assignmentInstance, string argumentName) 66 | { 67 | if (assignmentTargetType == (Type)null) 68 | { 69 | throw new ArgumentNullException("assignmentTargetType"); 70 | } 71 | if (assignmentInstance == null) 72 | { 73 | throw new ArgumentNullException("assignmentInstance"); 74 | } 75 | if (assignmentTargetType.GetTypeInfo().IsAssignableFrom(assignmentInstance.GetType().GetTypeInfo())) 76 | { 77 | return; 78 | } 79 | throw new ArgumentException(string.Format("The type {1} cannot be assigned to variables of type {0}.", new object[2] 80 | { 81 | assignmentTargetType, 82 | Guard.GetTypeName(assignmentInstance) 83 | }), argumentName); 84 | } 85 | 86 | private static string GetTypeName(object assignmentInstance) 87 | { 88 | try 89 | { 90 | return assignmentInstance.GetType().FullName; 91 | } 92 | catch (Exception) 93 | { 94 | return ""; 95 | } 96 | } 97 | } 98 | } 99 | -------------------------------------------------------------------------------- /AutoCopyLib/Utilities/StaticReflection.cs: -------------------------------------------------------------------------------- 1 | // Original C# code written by 2 | // Unity - https://github.com/unitycontainer/unity 3 | // Copyright (C) 2015-2017 Microsoft 4 | // 5 | // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this product except in 6 | // compliance with the License. You may obtain a copy of the License at 7 | // 8 | // http://www.apache.org/licenses/LICENSE-2.0 9 | // 10 | // Unless required by applicable law or agreed to in writing, software distributed under the License is 11 | // distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and limitations under the License. 13 | // 14 | 15 | using System; 16 | using System.Linq.Expressions; 17 | using System.Reflection; 18 | 19 | namespace AutoCopyLib.Utilities 20 | { 21 | public static class StaticReflection 22 | { 23 | public static MethodInfo GetMethodInfo(Expression expression) 24 | { 25 | return StaticReflection.GetMethodInfo((LambdaExpression)expression); 26 | } 27 | public static MethodInfo GetMethodInfo(Expression> expression) 28 | { 29 | return StaticReflection.GetMethodInfo((LambdaExpression)expression); 30 | } 31 | public static MethodInfo GetMethodInfo(Expression> expression) 32 | { 33 | return StaticReflection.GetMethodInfo((LambdaExpression)expression); 34 | } 35 | public static MethodInfo GetMethodInfo(Expression> expression) 36 | { 37 | return StaticReflection.GetMethodInfo((LambdaExpression)expression); 38 | } 39 | 40 | private static MethodInfo GetMethodInfo(LambdaExpression lambda) 41 | { 42 | StaticReflection.GuardProperExpressionForm(lambda.Body); 43 | return ((MethodCallExpression)lambda.Body).Method; 44 | } 45 | 46 | public static MethodInfo GetPropertyGetMethodInfo(Expression> expression) 47 | { 48 | MethodInfo getMethod = StaticReflection.GetPropertyInfo(expression).GetGetMethod(true); 49 | if (getMethod == (MethodInfo)null) 50 | { 51 | throw new InvalidOperationException("Invalid expression form passed"); 52 | } 53 | return getMethod; 54 | } 55 | 56 | public static MethodInfo GetPropertySetMethodInfo(Expression> expression) 57 | { 58 | MethodInfo setMethod = StaticReflection.GetPropertyInfo(expression).GetSetMethod(true); 59 | if (setMethod == (MethodInfo)null) 60 | { 61 | throw new InvalidOperationException("Invalid expression form passed"); 62 | } 63 | return setMethod; 64 | } 65 | 66 | private static PropertyInfo GetPropertyInfo(LambdaExpression lambda) 67 | { 68 | MemberExpression obj = lambda.Body as MemberExpression; 69 | if (obj == null) 70 | { 71 | throw new InvalidOperationException("Invalid expression form passed"); 72 | } 73 | PropertyInfo obj2 = obj.Member as PropertyInfo; 74 | if (obj2 == (PropertyInfo)null) 75 | { 76 | throw new InvalidOperationException("Invalid expression form passed"); 77 | } 78 | return obj2; 79 | } 80 | 81 | public static MemberInfo GetMemberInfo(Expression> expression) 82 | { 83 | Guard.ArgumentNotNull(expression, "expression"); 84 | MemberExpression obj = expression.Body as MemberExpression; 85 | if (obj == null) 86 | { 87 | throw new InvalidOperationException("invalid expression form passed"); 88 | } 89 | MemberInfo member = obj.Member; 90 | if (member == (MemberInfo)null) 91 | { 92 | throw new InvalidOperationException("Invalid expression form passed"); 93 | } 94 | return member; 95 | } 96 | 97 | public static ConstructorInfo GetConstructorInfo(Expression> expression) 98 | { 99 | Guard.ArgumentNotNull(expression, "expression"); 100 | NewExpression obj = expression.Body as NewExpression; 101 | if (obj == null) 102 | { 103 | throw new InvalidOperationException("Invalid expression form passed"); 104 | } 105 | return obj.Constructor; 106 | } 107 | 108 | private static void GuardProperExpressionForm(Expression expression) 109 | { 110 | if (expression.NodeType == ExpressionType.Call) 111 | { 112 | return; 113 | } 114 | throw new InvalidOperationException("Invalid expression form passed"); 115 | } 116 | } 117 | } 118 | -------------------------------------------------------------------------------- /AutoCopyLib/Utilities/VariableGenerator.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Linq.Expressions; 3 | 4 | namespace AutoCopyLib.Utilities 5 | { 6 | public static class VariableGenerator 7 | { 8 | private static int index = 0; 9 | public static ParameterExpression Generate(Type type) 10 | { 11 | return Expression.Variable(type, $"var{++index}"); 12 | } 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /AutoCopyLib/Visitors/ConditionFalseRewriter.cs: -------------------------------------------------------------------------------- 1 | using System.Linq.Expressions; 2 | 3 | namespace AutoCopyLib.Visitors 4 | { 5 | public class ConditionFalseRewriter : ExpressionVisitor 6 | { 7 | private Expression _ifFalse; 8 | public ConditionFalseRewriter(Expression ifFalse) 9 | { 10 | _ifFalse = ifFalse; 11 | } 12 | protected override Expression VisitConditional(ConditionalExpression node) 13 | { 14 | if (node.IfFalse == null || node.IfFalse.NodeType == ExpressionType.Default) 15 | { 16 | return node.Update(this.Visit(node.Test), this.Visit(node.IfTrue), this.Visit(_ifFalse)); 17 | } 18 | return base.VisitConditional(node); 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /AutoCopyLib/Visitors/FunctionCompositionExtensions.cs: -------------------------------------------------------------------------------- 1 | //using AutoMapper; 2 | //using AutoMapper.QueryableExtensions; 3 | using System; 4 | //using System.Collections.Concurrent; 5 | //using System.Collections.Generic; 6 | //using System.Linq; 7 | using System.Linq.Expressions; 8 | //using System.Reflection; 9 | //using System.Text; 10 | //using System.Threading.Tasks; 11 | 12 | namespace AutoCopyLib 13 | { 14 | [Obsolete] 15 | public static class FunctionCompositionExtensions 16 | { 17 | //private static ConcurrentDictionary, Tuple> dictionary = new ConcurrentDictionary, Tuple>(); 18 | //private static MethodInfo method = typeof(FunctionCompositionExtensions).GetMethod("Compose", BindingFlags.NonPublic | BindingFlags.Static); 19 | 20 | //public static Expression> MapExpression(this Expression> selector) 21 | //{ 22 | // var bulidMethod = dictionary.GetOrAdd(new Tuple(typeof(S), typeof(D)), _ => 23 | // { 24 | // var expression = Mapper.Engine.CreateMapExpression(); 25 | // return new Tuple(method.MakeGenericMethod(typeof(D), typeof(bool), typeof(S)), expression); 26 | // }); 27 | // return bulidMethod.Item1.Invoke(null, new[] { selector, bulidMethod.Item2 }) as Expression>; 28 | 29 | //} 30 | 31 | //static Expression> Compose(this Expression> outer, Expression> inner) 32 | //{ 33 | // return Expression.Lambda>( 34 | // ParameterReplacer.Replace(outer.Body, outer.Parameters[0], inner.Body), 35 | // inner.Parameters[0]); 36 | //} 37 | 38 | //static Expression> ComposePredicate(this Expression> outer, Expression> inner) 39 | //{ 40 | // return Expression.Lambda>( 41 | // ParameterReplacer.Replace(outer.Body, outer.Parameters[0], inner.Body), 42 | // inner.Parameters[0]); 43 | //} 44 | } 45 | internal class ParameterReplacer : ExpressionVisitor 46 | { 47 | private ParameterExpression[] _parameters; 48 | private Expression[] _replacements; 49 | private int _length; 50 | 51 | private ParameterReplacer(ParameterExpression[] parameters, Expression[] replacements) 52 | { 53 | _parameters = parameters; 54 | _replacements = replacements; 55 | _length = _parameters.Length; 56 | } 57 | 58 | public static Expression Replace(Expression expression, ParameterExpression[] parameters, Expression[] replacements) 59 | { 60 | if (parameters == null || parameters.Length == 0) 61 | throw new ArgumentException($"the parameter {nameof(parameters)} cannot be null or empty"); 62 | if (replacements == null || replacements.Length == 0) 63 | throw new ArgumentException($"the parameter {nameof(replacements)} cannot be null or empty"); 64 | if (parameters.Length != replacements.Length) 65 | throw new ArgumentException($"the length of {nameof(parameters)} must be equal to the length of {nameof(replacements)}"); 66 | return new ParameterReplacer(parameters, replacements).Visit(expression); 67 | } 68 | 69 | protected override Expression VisitParameter(ParameterExpression parameter) 70 | { 71 | for (int i = 0; i < _length;i++) 72 | { 73 | if (parameter.Type == _parameters[i].Type && parameter.Name==_parameters[i].Name) 74 | { 75 | return _replacements[i]; 76 | } 77 | } 78 | return base.VisitParameter(parameter); 79 | } 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /AutoCopyLib/Visitors/GetTryBodyRewriter.cs: -------------------------------------------------------------------------------- 1 | using System.Linq.Expressions; 2 | 3 | namespace AutoCopyLib 4 | { 5 | public partial class AutoCopy 6 | { 7 | internal class GetTryBodyRewriter:ExpressionVisitor 8 | { 9 | private Expression _body; 10 | private Expression _node; 11 | public GetTryBodyRewriter(Expression node) 12 | { 13 | _node = node; 14 | Visit(_node); 15 | } 16 | protected override Expression VisitTry(TryExpression node) 17 | { 18 | _body = node.Body; 19 | return base.VisitTry(node); 20 | } 21 | public Expression Body 22 | { 23 | get 24 | { 25 | return _body; 26 | } 27 | } 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /AutoCopyLib/Visitors/NullsafeQueryRewriter.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq.Expressions; 4 | using System.Reflection; 5 | using System.Runtime.CompilerServices; 6 | 7 | namespace AutoCopyLib 8 | { 9 | public partial class AutoCopy 10 | { 11 | #region copied from NeinLinq (MIT License): https://github.com/axelheer/nein-linq/blob/master/src/NeinLinq/NullsafeQueryRewriter.cs 12 | internal class NullsafeQueryRewriter : ExpressionVisitor 13 | { 14 | private static readonly LockingConcurrentDictionary cache = new LockingConcurrentDictionary(new Func(NullsafeQueryRewriter.Fallback)); 15 | protected override Expression VisitMember(MemberExpression node) 16 | { 17 | if (node == null) 18 | throw new ArgumentException(nameof(node)); 19 | var target = Visit(node.Expression); 20 | if(!IsSafe(target)) 21 | { 22 | return BeSafe(target, node, node.Update); 23 | } 24 | return node.Update(target); 25 | } 26 | protected override Expression VisitMethodCall(MethodCallExpression node) 27 | { 28 | if (node == null) 29 | throw new ArgumentNullException(nameof(node)); 30 | 31 | var target = Visit(node.Object); 32 | 33 | if (!IsSafe(target)) 34 | { 35 | // insert null-check before invoking instance method 36 | return BeSafe(target, node, fallback => node.Update(fallback, node.Arguments)); 37 | } 38 | 39 | var arguments = Visit(node.Arguments); 40 | 41 | if (IsExtensionMethod(node.Method) && !IsSafe(arguments[0])) 42 | { 43 | // insert null-check before invoking extension method 44 | return BeSafe(arguments[0], node.Update(null, arguments), fallback => 45 | { 46 | var args = new Expression[arguments.Count]; 47 | arguments.CopyTo(args, 0); 48 | args[0] = fallback; 49 | 50 | return node.Update(null, args); 51 | }); 52 | } 53 | 54 | return node.Update(target, arguments); 55 | } 56 | public Expression visit(Expression node) 57 | { 58 | return this.Visit(node); 59 | } 60 | static bool IsSafe(Expression expression) 61 | { 62 | // in method call results and constant values we trust to avoid too much conditions... 63 | return expression == null 64 | || expression.NodeType == ExpressionType.Call 65 | || expression.NodeType == ExpressionType.Constant 66 | || !IsNullableOrReferenceType(expression.Type); 67 | } 68 | static bool IsNullableOrReferenceType(Type type) 69 | { 70 | return !type.GetTypeInfo().IsValueType || Nullable.GetUnderlyingType(type) != null; 71 | } 72 | static Expression BeSafe(Expression target, Expression expression, Func update) 73 | { 74 | var fallback = cache.GetOrAdd(target.Type); 75 | 76 | if (fallback != null) 77 | { 78 | // coalesce instead, a bit intrusive but fast... 79 | return update(Expression.Coalesce(target, fallback)); 80 | } 81 | 82 | // target can be null, which is why we are actually here... 83 | var targetFallback = Expression.Constant(null, target.Type); 84 | 85 | // expression can be default or null, which is basically the same... 86 | var expressionFallback = !IsNullableOrReferenceType(expression.Type) 87 | ? (Expression)Expression.Default(expression.Type) : Expression.Constant(null, expression.Type); 88 | 89 | return Expression.Condition(Expression.Equal(target, targetFallback), expressionFallback, expression); 90 | } 91 | static Expression Fallback(Type type) 92 | { 93 | // default values for generic collections 94 | if (type.IsConstructedGenericType && type.GenericTypeArguments.Length == 1) 95 | { 96 | return CollectionFallback(typeof(List<>), type) 97 | ?? CollectionFallback(typeof(HashSet<>), type); 98 | } 99 | 100 | // default value for arrays 101 | if (type.IsArray) 102 | { 103 | return Expression.NewArrayInit(type.GetElementType()); 104 | } 105 | 106 | return null; 107 | } 108 | 109 | static Expression CollectionFallback(Type definition, Type type) 110 | { 111 | var collection = definition.MakeGenericType(type.GenericTypeArguments); 112 | 113 | // try if an instance of this collection would suffice 114 | if (type.GetTypeInfo().IsAssignableFrom(collection.GetTypeInfo())) 115 | { 116 | return Expression.Convert(Expression.New(collection), type); 117 | } 118 | 119 | return null; 120 | } 121 | 122 | static bool IsExtensionMethod(MethodInfo element) 123 | { 124 | return element.IsDefined(typeof(ExtensionAttribute), false); 125 | } 126 | } 127 | #endregion 128 | } 129 | } 130 | -------------------------------------------------------------------------------- /AutoCopyLib/Visitors/ReturnTargetRewriter.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Linq.Expressions; 3 | 4 | namespace AutoCopyLib.Visitors 5 | { 6 | public class ReturnTargetRewriter : ExpressionVisitor 7 | { 8 | private LabelTarget _returnTarget; 9 | private Expression _defaultValue; 10 | private Expression _ifTure; 11 | public ReturnTargetRewriter(Type returnType, Expression defaultValue) 12 | { 13 | _returnTarget = Expression.Label(returnType); 14 | _defaultValue = defaultValue; 15 | } 16 | protected override Expression VisitParameter(ParameterExpression node) 17 | { 18 | if (_ifTure == null && node.Type == _returnTarget.Type) 19 | _ifTure = node; 20 | return node; 21 | } 22 | protected override LabelTarget VisitLabelTarget(LabelTarget node) 23 | { 24 | return _returnTarget; 25 | } 26 | protected override Expression VisitLabel(LabelExpression node) 27 | { 28 | return node.Update(this.VisitLabelTarget(node.Target), _defaultValue); 29 | } 30 | protected override Expression VisitGoto(GotoExpression node) 31 | { 32 | var constant = node.Value as ConstantExpression; 33 | Expression value = _defaultValue; 34 | if (constant != null && (bool)constant.Value) 35 | value = _ifTure; 36 | return node.Update(this.VisitLabelTarget(node.Target), value); 37 | } 38 | public LabelTarget LabelTarget 39 | { 40 | get 41 | { 42 | return _returnTarget; 43 | } 44 | } 45 | public Expression DefaultValue 46 | { 47 | get 48 | { 49 | return _defaultValue; 50 | } 51 | } 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /Console.Test/App.config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | -------------------------------------------------------------------------------- /Console.Test/Clock.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Diagnostics; 4 | using System.Linq; 5 | using System.Threading; 6 | 7 | //copied from https://stackoverflow.com/questions/969290/exact-time-measurement-for-performance-testing 8 | namespace Benchmark 9 | { 10 | public static class Extensions 11 | { 12 | public static double NormalizedMean(this ICollection values) 13 | { 14 | if (values.Count == 0) 15 | return double.NaN; 16 | 17 | var deviations = values.Deviations().ToArray(); 18 | var meanDeviation = deviations.Sum(t => Math.Abs(t.Item2)) / values.Count; 19 | return deviations.Where(t => t.Item2 > 0 || Math.Abs(t.Item2) <= meanDeviation).Average(t => t.Item1); 20 | } 21 | 22 | public static IEnumerable> Deviations(this ICollection values) 23 | { 24 | if (values.Count == 0) 25 | yield break; 26 | 27 | var avg = values.Average(); 28 | foreach (var d in values) 29 | yield return Tuple.Create(d, avg - d); 30 | } 31 | } 32 | public class Clock 33 | { 34 | interface IStopwatch 35 | { 36 | bool IsRunning { get; } 37 | TimeSpan Elapsed { get; } 38 | 39 | void Start(); 40 | void Stop(); 41 | void Reset(); 42 | } 43 | 44 | 45 | 46 | class TimeWatch : IStopwatch 47 | { 48 | Stopwatch stopwatch = new Stopwatch(); 49 | 50 | public TimeSpan Elapsed 51 | { 52 | get { return stopwatch.Elapsed; } 53 | } 54 | 55 | public bool IsRunning 56 | { 57 | get { return stopwatch.IsRunning; } 58 | } 59 | 60 | 61 | 62 | public TimeWatch() 63 | { 64 | if (!Stopwatch.IsHighResolution) 65 | throw new NotSupportedException("Your hardware doesn't support high resolution counter"); 66 | 67 | //prevent the JIT Compiler from optimizing Fkt calls away 68 | long seed = Environment.TickCount; 69 | 70 | //use the second Core/Processor for the test 71 | Process.GetCurrentProcess().ProcessorAffinity = new IntPtr(2); 72 | 73 | //prevent "Normal" Processes from interrupting Threads 74 | Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.High; 75 | 76 | //prevent "Normal" Threads from interrupting this thread 77 | Thread.CurrentThread.Priority = ThreadPriority.Highest; 78 | } 79 | 80 | 81 | 82 | public void Start() 83 | { 84 | stopwatch.Start(); 85 | } 86 | 87 | public void Stop() 88 | { 89 | stopwatch.Stop(); 90 | } 91 | 92 | public void Reset() 93 | { 94 | stopwatch.Reset(); 95 | } 96 | } 97 | 98 | 99 | 100 | class CpuWatch : IStopwatch 101 | { 102 | TimeSpan startTime; 103 | TimeSpan endTime; 104 | bool isRunning; 105 | 106 | 107 | 108 | public TimeSpan Elapsed 109 | { 110 | get 111 | { 112 | if (IsRunning) 113 | throw new NotImplementedException("Getting elapsed span while watch is running is not implemented"); 114 | 115 | return endTime - startTime; 116 | } 117 | } 118 | 119 | public bool IsRunning 120 | { 121 | get { return isRunning; } 122 | } 123 | 124 | 125 | 126 | public void Start() 127 | { 128 | startTime = Process.GetCurrentProcess().TotalProcessorTime; 129 | isRunning = true; 130 | } 131 | 132 | public void Stop() 133 | { 134 | endTime = Process.GetCurrentProcess().TotalProcessorTime; 135 | isRunning = false; 136 | } 137 | 138 | public void Reset() 139 | { 140 | startTime = TimeSpan.Zero; 141 | endTime = TimeSpan.Zero; 142 | } 143 | } 144 | 145 | 146 | 147 | public static void BenchmarkTime(string name, Action action, int iterations = 10000) 148 | { 149 | Benchmark(name, action, iterations); 150 | } 151 | 152 | static void Benchmark(string name, Action action, int iterations) where T : IStopwatch, new() 153 | { 154 | //clean Garbage 155 | GC.Collect(); 156 | 157 | //wait for the finalizer queue to empty 158 | GC.WaitForPendingFinalizers(); 159 | 160 | //clean Garbage 161 | GC.Collect(); 162 | 163 | //warm up 164 | action(); 165 | 166 | var stopwatch = new T(); 167 | var timings = new double[5]; 168 | for (int i = 0; i < timings.Length; i++) 169 | { 170 | stopwatch.Reset(); 171 | stopwatch.Start(); 172 | for (int j = 0; j < iterations; j++) 173 | action(); 174 | stopwatch.Stop(); 175 | timings[i] = stopwatch.Elapsed.TotalMilliseconds; 176 | } 177 | System.Console.WriteLine($"{name} executed normalized mean : " + timings.NormalizedMean().ToString()); 178 | } 179 | 180 | public static void BenchmarkCpu(string name, Action action, int iterations = 10000) 181 | { 182 | Benchmark(name, action, iterations); 183 | } 184 | } 185 | } 186 | -------------------------------------------------------------------------------- /Console.Test/Console.Test.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {619CDDB5-2283-499C-BEFB-7B32C10FAEA7} 8 | Exe 9 | Properties 10 | Benchmark 11 | Benchmark 12 | v4.5 13 | 512 14 | publish\ 15 | true 16 | Disk 17 | false 18 | Foreground 19 | 7 20 | Days 21 | false 22 | false 23 | true 24 | 0 25 | 1.0.0.%2a 26 | false 27 | false 28 | true 29 | 30 | 31 | 32 | AnyCPU 33 | true 34 | full 35 | false 36 | bin\Debug\ 37 | DEBUG;TRACE 38 | prompt 39 | 4 40 | false 41 | 42 | 43 | AnyCPU 44 | pdbonly 45 | true 46 | bin\Release\ 47 | TRACE 48 | prompt 49 | 4 50 | false 51 | 52 | 53 | 54 | ..\packages\AutoMapper.6.2.2\lib\net45\AutoMapper.dll 55 | True 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | False 80 | Microsoft .NET Framework 4.5 %28x86 和 x64%29 81 | true 82 | 83 | 84 | False 85 | .NET Framework 3.5 SP1 86 | false 87 | 88 | 89 | 90 | 91 | {c2685dab-9618-4fdc-8e85-248e1069ac39} 92 | AutoCopyLib 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 107 | -------------------------------------------------------------------------------- /Console.Test/Program.cs: -------------------------------------------------------------------------------- 1 | using AutoCopyLib; 2 | using System; 3 | using System.Diagnostics; 4 | 5 | namespace Benchmark 6 | { 7 | public class Address 8 | { 9 | public string ZipCode { get; set; } 10 | } 11 | public class Telephone 12 | { 13 | public string Number { get; set; } 14 | } 15 | 16 | public class Customer 17 | { 18 | public Address Address { get; set; } 19 | public Telephone Phone { get; set; } 20 | public string Memo { get; set; } 21 | } 22 | public class CustomerInfo 23 | { 24 | public string zipCode { get; set; } 25 | public string PhoneNumber { get; set; } 26 | public string Memo { get; set; } 27 | } 28 | class Program 29 | { 30 | static void Main(string[] args) 31 | { 32 | var autoCopy = AutoCopy.CreateMap(); 33 | autoCopy 34 | .ForMember(p => p.zipCode, opt => opt.MapFrom(p => p.Address.ZipCode)) 35 | .ForMember(p => p.PhoneNumber, opt => opt.MapFrom(p => p.Phone.Number)); 36 | autoCopy.Register(); 37 | 38 | AutoMapper.Mapper.Initialize(cfg => 39 | cfg.CreateMap() 40 | .ForMember(p => p.zipCode, opt => opt.MapFrom(p => p.Address.ZipCode)) 41 | .ForMember(p => p.PhoneNumber, opt => opt.MapFrom(p => p.Phone.Number)) 42 | ); 43 | #if !DEBUG 44 | int loop = 100000; 45 | #else 46 | int loop = 10; 47 | #endif 48 | Clock.BenchmarkTime("hand map",() => 49 | { 50 | Customer customer = new Customer(); 51 | CustomerInfo customerInfo = new CustomerInfo(); 52 | customer.Address = new Address { ZipCode = "1234567890" }; 53 | customer.Phone = new Telephone { Number = "17791704580" }; 54 | customer.Memo = "customer"; 55 | ShallowCopy(customerInfo, customer); 56 | }, loop); 57 | 58 | Clock.BenchmarkTime("AutoCopy",() => 59 | { 60 | Customer customer = new Customer(); 61 | CustomerInfo customerInfo = new CustomerInfo(); 62 | customer.Address = new Address { ZipCode = "1234567890" }; 63 | customer.Phone = new Telephone { Number = "17791704580" }; 64 | customer.Memo = "customer"; 65 | autoCopy.ShallowCopy(customer, customerInfo); 66 | }, loop); 67 | 68 | Clock.BenchmarkTime("AutoMapper",() => 69 | { 70 | Customer customer = new Customer(); 71 | customer.Address = new Address { ZipCode = "1234567890" }; 72 | customer.Phone = new Telephone { Number = "17791704580" }; 73 | customer.Memo = "customer"; 74 | var customerInfo=AutoMapper.Mapper.Map(customer); 75 | }, loop); 76 | } 77 | static bool ShallowCopy(CustomerInfo customerInfo, Customer customer) 78 | { 79 | try 80 | { 81 | customerInfo = customerInfo ?? new CustomerInfo(); 82 | customerInfo.PhoneNumber = customer.Phone.Number; 83 | customerInfo.zipCode = customer.Address.ZipCode; 84 | customerInfo.Memo = customer.Memo; 85 | return true; 86 | } 87 | catch (Exception) 88 | { 89 | return false; 90 | } 91 | } 92 | } 93 | } 94 | -------------------------------------------------------------------------------- /Console.Test/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // 有关程序集的一般信息由以下 6 | // 控制。更改这些特性值可修改 7 | // 与程序集关联的信息。 8 | [assembly: AssemblyTitle("Console.Test")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("")] 12 | [assembly: AssemblyProduct("Console.Test")] 13 | [assembly: AssemblyCopyright("Copyright © 2017")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | //将 ComVisible 设置为 false 将使此程序集中的类型 18 | //对 COM 组件不可见。 如果需要从 COM 访问此程序集中的类型, 19 | //请将此类型的 ComVisible 特性设置为 true。 20 | [assembly: ComVisible(false)] 21 | 22 | // 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID 23 | [assembly: Guid("619cddb5-2283-499c-befb-7b32c10faea7")] 24 | 25 | // 程序集的版本信息由下列四个值组成: 26 | // 27 | // 主版本 28 | // 次版本 29 | // 生成号 30 | // 修订号 31 | // 32 | //可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值, 33 | // 方法是按如下所示使用“*”: : 34 | // [assembly: AssemblyVersion("1.0.*")] 35 | [assembly: AssemblyVersion("1.0.0.0")] 36 | [assembly: AssemblyFileVersion("1.0.0.0")] 37 | -------------------------------------------------------------------------------- /Console.Test/packages.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | -------------------------------------------------------------------------------- /DataRowTest/App.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /DataRowTest/DataRowExpressionProvider.cs: -------------------------------------------------------------------------------- 1 | using AutoCopyLib; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | using System.Linq.Expressions; 6 | using System.Text; 7 | using System.Threading.Tasks; 8 | 9 | namespace DataRowTest 10 | { 11 | internal sealed class DataRowExpressionProvider : TargetExpressionProviderBase 12 | { 13 | public DataRowExpressionProvider(Type targetType) : base(targetType) 14 | { 15 | } 16 | 17 | public override bool TryGetExpression(string name, ParameterExpression parameter, Type destType, out Expression exp, out ParameterExpression variable, out Expression test, out bool ifTrue) 18 | { 19 | exp = null; 20 | test = null; 21 | variable = null; 22 | ifTrue = true; 23 | try 24 | { 25 | exp = Expression.Convert(Expression.Property(parameter, "Item", Expression.Constant(name, typeof(string))),destType); 26 | test = Expression.Not(Expression.TypeIs(Expression.Property(parameter, "Item", Expression.Constant(name, typeof(string))), typeof(DBNull))); 27 | return true; 28 | } 29 | catch 30 | { 31 | return false; 32 | } 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /DataRowTest/DataRowTest.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {FB83AFCB-3523-47D7-B849-A9032294EC46} 8 | Exe 9 | Properties 10 | DataRowTest 11 | DataRowTest 12 | v4.5 13 | 512 14 | 15 | 16 | AnyCPU 17 | true 18 | full 19 | false 20 | bin\Debug\ 21 | DEBUG;TRACE 22 | prompt 23 | 4 24 | 25 | 26 | AnyCPU 27 | pdbonly 28 | true 29 | bin\Release\ 30 | TRACE 31 | prompt 32 | 4 33 | 34 | 35 | 36 | ..\packages\AgileObjects.NetStandardPolyfills.1.2.0\lib\net40\AgileObjects.NetStandardPolyfills.dll 37 | True 38 | 39 | 40 | ..\packages\AgileObjects.ReadableExpressions.1.10.0\lib\net40\AgileObjects.ReadableExpressions.dll 41 | True 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | {c2685dab-9618-4fdc-8e85-248e1069ac39} 65 | AutoCopyLib 66 | 67 | 68 | 69 | 76 | -------------------------------------------------------------------------------- /DataRowTest/Program.cs: -------------------------------------------------------------------------------- 1 | using AgileObjects.ReadableExpressions; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Data; 5 | using System.Linq; 6 | using System.Text; 7 | using System.Threading.Tasks; 8 | 9 | namespace DataRowTest 10 | { 11 | class Program 12 | { 13 | static void Main(string[] args) 14 | { 15 | var autoCopy = AutoCopyLib.AutoCopy.CreateMap(); 16 | autoCopy.Provider = new DataRowExpressionProvider(typeof(DataRowView)); 17 | autoCopy.Register(); 18 | Console.WriteLine(autoCopy.Lambda.ToReadableString()); 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /DataRowTest/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // 有关程序集的一般信息由以下 6 | // 控制。更改这些特性值可修改 7 | // 与程序集关联的信息。 8 | [assembly: AssemblyTitle("DataRowTest")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("")] 12 | [assembly: AssemblyProduct("DataRowTest")] 13 | [assembly: AssemblyCopyright("Copyright © 2017")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | //将 ComVisible 设置为 false 将使此程序集中的类型 18 | //对 COM 组件不可见。 如果需要从 COM 访问此程序集中的类型, 19 | //请将此类型的 ComVisible 特性设置为 true。 20 | [assembly: ComVisible(false)] 21 | 22 | // 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID 23 | [assembly: Guid("fb83afcb-3523-47d7-b849-a9032294ec46")] 24 | 25 | // 程序集的版本信息由下列四个值组成: 26 | // 27 | // 主版本 28 | // 次版本 29 | // 生成号 30 | // 修订号 31 | // 32 | //可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值, 33 | // 方法是按如下所示使用“*”: : 34 | // [assembly: AssemblyVersion("1.0.*")] 35 | [assembly: AssemblyVersion("1.0.0.0")] 36 | [assembly: AssemblyFileVersion("1.0.0.0")] 37 | -------------------------------------------------------------------------------- /DataRowTest/SimpleModel.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace DataRowTest 4 | { 5 | public class SimpleModel 6 | { 7 | #region 变量定义 8 | 9 | private int _id = -1; 10 | 11 | private string _title = String.Empty; 12 | 13 | private string _gotourl = String.Empty; 14 | 15 | private DateTime _stime = DateTime.Now; 16 | 17 | private DateTime _etime = DateTime.Now; 18 | 19 | private string _runHour = String.Empty; 20 | 21 | private string _beizhu = String.Empty; 22 | 23 | private int _state = -1; 24 | 25 | private short _clickType = -1; 26 | 27 | private string _apkurl = String.Empty; 28 | 29 | private string _packageName = String.Empty; 30 | 31 | private string _mD5 = String.Empty; 32 | 33 | private short _silence = -1; 34 | #endregion 35 | 36 | #region 构造函数 37 | 38 | ///

39 | /// 40 | /// 41 | public SimpleModel() 42 | { 43 | } 44 | /// 45 | /// 46 | /// 47 | public SimpleModel 48 | ( 49 | int id, 50 | string title, 51 | string gotourl, 52 | DateTime stime, 53 | DateTime etime, 54 | string runHour, 55 | string beizhu, 56 | int state, 57 | short clickType, 58 | string apkurl, 59 | string packageName, 60 | string mD5, 61 | short silence 62 | ) 63 | { 64 | _id = id; 65 | _title = title; 66 | _gotourl = gotourl; 67 | _stime = stime; 68 | _etime = etime; 69 | _runHour = runHour; 70 | _beizhu = beizhu; 71 | _state = state; 72 | _clickType = clickType; 73 | _apkurl = apkurl; 74 | _packageName = packageName; 75 | _mD5 = mD5; 76 | _silence = silence; 77 | 78 | } 79 | #endregion 80 | 81 | #region 公共属性 82 | 83 | 84 | /// 85 | /// 86 | /// 87 | public int id 88 | { 89 | get { return _id; } 90 | set { _id = value; } 91 | } 92 | 93 | public string Title 94 | { 95 | get { return _title; } 96 | set { _title = value; } 97 | } 98 | 99 | public string Gotourl 100 | { 101 | get { return _gotourl; } 102 | set { _gotourl = value; } 103 | } 104 | 105 | public DateTime Stime 106 | { 107 | get { return _stime; } 108 | set { _stime = value; } 109 | } 110 | 111 | public DateTime Etime 112 | { 113 | get { return _etime; } 114 | set { _etime = value; } 115 | } 116 | 117 | public string RunHour 118 | { 119 | get { return _runHour; } 120 | set { _runHour = value; } 121 | } 122 | 123 | public string Beizhu 124 | { 125 | get { return _beizhu; } 126 | set { _beizhu = value; } 127 | } 128 | 129 | public int State 130 | { 131 | get { return _state; } 132 | set { _state = value; } 133 | } 134 | 135 | public short ClickType 136 | { 137 | get { return _clickType; } 138 | set { _clickType = value; } 139 | } 140 | 141 | public string Apkurl 142 | { 143 | get { return _apkurl; } 144 | set { _apkurl = value; } 145 | } 146 | 147 | public string PackageName 148 | { 149 | get { return _packageName; } 150 | set { _packageName = value; } 151 | } 152 | 153 | public string MD5 154 | { 155 | get { return _mD5; } 156 | set { _mD5 = value; } 157 | } 158 | 159 | public short Silence 160 | { 161 | get { return _silence; } 162 | set { _silence = value; } 163 | } 164 | 165 | #endregion 166 | 167 | } 168 | } 169 | -------------------------------------------------------------------------------- /DataRowTest/packages.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2017 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## AutoCopy 2 | 3 | AutoCopy is a tool that reduces development time and helps programmers get out of some heavy human coding, which is inspired by **[AutoMapper](https://github.com/AutoMapper/AutoMapper "AutoMapper")**. 4 | 5 | ## Document 6 | 7 | [Chinese](README_CN.md) 8 | 9 | ## Dependencies 10 | 11 | * **[Mono.Reflection.dll](https://github.com/jbevain/mono.reflection "Mono.Reflection")** 12 | * **[DelegateDecompiler.dll](https://github.com/hazzik/DelegateDecompiler "DelegateDecompiler")** 13 | 14 | ## Attribute 15 | 16 | 1. Fast execution 17 | 2. Based on the abstract class **TargetExpressionProviderBase** can be any extension 18 | 3. Support automatic / manual type conversion 19 | 4. Support for multiple instances of AutoCopy nesting 20 | 21 | ## Benchmark 22 | 23 | iterations:100,000 24 | 25 | | Action | mean time(ms) 26 | ---|--- 27 | hand map | 4.267375 28 | AutoCopy | 4.18163333333333 29 | AutoMapper | 42.4985 30 | 31 | iterations:1,000,000 32 | 33 | | Action | mean time(ms) 34 | ---|--- 35 | hand map | 30.884225 36 | AutoCopy | 38.647675 37 | AutoMapper | 322.8877 38 | 39 | iterations:10,000,000 40 | 41 | | Action | mean time(ms) 42 | ---|--- 43 | hand map | 440.14825 44 | AutoCopy | 459.17575 45 | AutoMapper | 3895.974725 46 | 47 | Benchmark code see [here](/Console.Test/Program.cs) 48 | 49 | ## Example 50 | 51 | ### 1 Same type of object copyed 52 | 53 | ```csharp 54 | 55 | public class Address 56 | { 57 | public string ZipCode { get; set; } 58 | } 59 | 60 | var autoCopy = AutoCopy.CreateMap(); 61 | 62 | autoCopy.Register(); 63 | 64 | Address a=new Address { ZipCode="1234567890"; }; 65 | 66 | Address b=autoCopy.Map(a); 67 | 68 | ``` 69 | 70 | ### 2 Different type of object copyed 71 | 72 | ```csharp 73 | 74 | public class Address 75 | { 76 | public string ZipCode { get; set; } 77 | } 78 | 79 | public class Telephone 80 | { 81 | public string Number { get; set; } 82 | } 83 | 84 | public class Customer 85 | { 86 | public Address Address { get; set; } 87 | public Telephone Phone { get; set; } 88 | public string Memo { get; set; } 89 | } 90 | 91 | public class CustomerInfo 92 | { 93 | public string zipCode { get; set; } 94 | public string PhoneNumber { get; set; } 95 | public string Memo { get; set; } 96 | } 97 | 98 | var autoCopy = AutoCopy.CreateMap(); 99 | 100 | autoCopy 101 | .ForMember(p => p.zipCode, opt => opt.MapFrom(p => p.Address.ZipCode)) 102 | .ForMember(p => p.PhoneNumber, opt => opt.MapFrom(p => p.Phone.Number)); 103 | 104 | autoCopy.Register(); 105 | 106 | Customer customer = new Customer(); 107 | 108 | customer.Address = new Address { ZipCode = "1234567890" }; 109 | 110 | customer.Phone = new Telephone { Number = "17791704580" }; 111 | 112 | customer.Memo = "Test"; 113 | 114 | CustomerInfo info = autoCopy.Map(customer); 115 | 116 | ``` 117 | 118 | ### 3 Multiple AutoCopy instances nested 119 | 120 | ```csharp 121 | 122 | public class Data 123 | { 124 | public int width { get; set; } 125 | public int height { get; set; } 126 | public string ua { get; set; } 127 | public string ip { get; set; } 128 | public string imei { get; set; } 129 | public string android_id { get; set; } 130 | public string make { get; set; } 131 | public string model { get; set; } 132 | public string os { get; set; } 133 | public string osv { get; set; } 134 | public int connectionType { get; set; } 135 | public int deviceType { get; set; } 136 | public string mac { get; set; } 137 | public int screenWidth { get; set; } 138 | public int screenHeight { get; set; } 139 | public string appName { get; set; } 140 | public int ppi { get; set; } 141 | public string dpidsha1 { get; set; } 142 | public string plmn { get; set; } 143 | public string orientation { get; set; } 144 | public int pos { get; set; } 145 | public bool instl { get; set; } 146 | public string ver { get; set; } 147 | public string bundle { get; set; } 148 | public Ext ext { get; set; } 149 | } 150 | public class Ext 151 | { 152 | public int ID { get; set; } 153 | } 154 | 155 | string surl = "id=10010&width=10&height=10&ua=ua&ip=127.0.0.1&imei=00000000000000&android_id=A00000000000000&make=1111111111&model=XXX&os=android&osv=4.0.1&connectionType=1&deviceType=1&mac=0.0.0.0.0.0.0&screenWidth=100&screenHeight=100&appName=test&ppi=600&dpidsha1=dpidsha1&plmn=1&orientation=1&pos=1&instl=true&ver=1.0.0&bundle=bundle"; 156 | 157 | HttpQueryCollection collection = new HttpQueryCollection(surl, false); 158 | 159 | var ac = AutoCopy.CreateMap(); 160 | 161 | ac.Provider= new HttpRequestParamsExpressionProvider(typeof(NameValueCollection)); 162 | 163 | var autoCopy = AutoCopy.CreateMap(); 164 | 165 | autoCopy.ForMember(p => p.ext, opt => opt.MapFrom(p=>ac.Map(p))); 166 | 167 | autoCopy.Provider = new HttpRequestParamsExpressionProvider(typeof(NameValueCollection)); 168 | 169 | autoCopy.Register(); 170 | 171 | Data data=autoCopy.Map(collection); 172 | 173 | ``` 174 | ## Type Convert 175 | ### Automatic conversion 176 | The TryConvert method of the internal class [TypeConverter](/AutoCopyLib/TypeConverter.cs) performs automatic conversion of the type in the following order: 177 | 178 | 1. Whether there is a explicit operator 179 | 2. Whether there is a implicit operator 180 | 3. Whether it is a subclass 181 | 4. Whether there is the Convert.ToXXX method 182 | 5. Whether there is the TryParse method on the target type 183 | 6. Call [Convert.ChangeType](https://msdn.microsoft.com/en-us/library/system.convert.changetype(v=vs.110).aspx "Convert.ChangeType") method 184 | ### Manual conversion 185 | 186 | Type conversions are registered by calling the **ForTypeConvert** method of the **AutoCopy** instance. 187 | 188 | ## Explanation of Parameter in [TryGetExpression](/AutoCopyLib/TargetExpressionProviderBase.cs) method 189 | 190 | With AutoCopy, assume T1 is the source type and T2 is the destination type 191 | 192 | | | Parameter Name | Description 193 | ---|---|--- 194 | 1 | name | destination property name 195 | 2 | parameter | Expression of source parameter Expression 196 | 3 | destType | destination type 197 | 4 | exp | the final Expression 198 | 5 | variable | variables 199 | 6 | test | test Expression 200 | 7 | ifTrue | Whether need to test or not; If the value is true, then only the test Expression executed return true can exp Expression will be called 201 | 202 | ## ChangeLog 203 | 2017-12-05 Add a demo which show the DataRow class convert to entity class 204 | 2017-12-12 Adjust the order of parameters in AutoCopy<,> and fixed the parameter type bug in Option.ResolveUsing 205 | 2017-12-26 Add the CopyMapAttribute attribute to support alias mapping of destination type property 206 | 2017-12-27 Add the CopyRequiredAttribute attribute to support the detection of the destination type property map value is required to be empty **[Need further testing]** 207 | 2017-12-28 Get a new LambdaExpression from the Decompiler function when another AutoCopy instance is called in the Option.MapFrom function 208 | 2018-01-12 Overload the Option.MapForm function, add a string parameter indicating the target's property name or mapping name 209 | 2018-02-09 fixed bug: When the CopyRequired attribute is applied to a property that requires nested mapping of an AutoCopy instance, called the Visit function of ConditionFalseRewriter class would cause error 210 | ## Warning 211 | 212 | Since AutoCopy uses reflection at runtime to analysis the properties of classes by calling **Register** methods automatically, bugs may occur if the source code is obfuscated. 213 | -------------------------------------------------------------------------------- /README_CN.md: -------------------------------------------------------------------------------- 1 | ## AutoCopy 2 | 3 | AutoCopy 一个可以缩短开发时间的工具类,帮助程序员从某些繁重的人肉编码中解脱出来。灵感来自于**[AutoMapper](https://github.com/AutoMapper/AutoMapper "AutoMapper")**,初次使用AutoMapper时被它实现的功能深深吸引,但是在逐渐学习中发现AutoMapper速度不能令人满意,并且实现有些复杂,小白不容易看懂原理,所以萌生了自己写一个更简单、更高效类库的想法。在这样一个契机之下,AutoCopy应运而生(:clap::smirk:)。AutoCopy的一些方法模仿了AutoMapper的命名和使用方式,降低使用上的难度。 4 | 5 | ## 文档 6 | 7 | [英文版](README.md) 8 | 9 | ## 依赖 10 | 11 | * **[Mono.Reflection.dll](https://github.com/jbevain/mono.reflection "Mono.Reflection")** 12 | * **[DelegateDecompiler.dll](https://github.com/hazzik/DelegateDecompiler "DelegateDecompiler")** 13 | 14 | ## 特性 15 | 16 | 1. 执行速度快 17 | 2. 基于抽象类**TargetExpressionProviderBase**可以实现任意扩展 18 | 3. 支持自动/手工的类型转换 19 | 4. 支持多AutoCopy实例嵌套 20 | 21 | ## 基准测试 22 | 23 | 24 | 执行次数:100,000 25 | 26 | | 操作 | 平均时间(毫秒) 27 | ---|--- 28 | 手动映射 | 4.267375 29 | AutoCopy | 4.18163333333333 30 | AutoMapper | 42.4985 31 | 32 | 执行次数:1,000,000 33 | 34 | | 操作 | 平均时间(毫秒) 35 | ---|--- 36 | 手动映射 | 30.884225 37 | AutoCopy | 38.647675 38 | AutoMapper | 322.8877 39 | 40 | 执行次数:10,000,000 41 | 42 | | 操作 | 平均时间(毫秒) 43 | ---|--- 44 | 手动映射 | 440.14825 45 | AutoCopy | 459.17575 46 | AutoMapper | 3895.974725 47 | 48 | Benchmark code see [here](/Console.Test/Program.cs) 49 | 50 | 51 | ## 原理说明 52 | 53 | 在调用**Register**方法时基于[Reflection](https://msdn.microsoft.com/en-us/library/system.reflection(v=vs.110).aspx "Reflection")分析源类和目标类的所有属性,并生成[Expression](https://msdn.microsoft.com/en-us/library/system.linq.expressions.expression(v=vs.110).aspx "Expression")列表,之后使用[Expression.Lambda](https://msdn.microsoft.com/en-us/library/system.linq.expressions.expression.lambda(v=vs.110).aspx "Expression.Lambda")方法把Expression列表以及相应参数包装成[LambdaExpression](https://msdn.microsoft.com/en-us/library/system.linq.expressions.lambdaexpression(v=vs.110).aspx "LambdaExpression"),通过调用Compile方法编译为[Func Delegate](https://msdn.microsoft.com/en-us/library/bb549151(v=vs.110).aspx "Func Delegate")。 54 | 55 | ## 示例 56 | 57 | ### 示例1 相同类型对象拷贝 58 | 59 | ```csharp 60 | 61 | public class Address 62 | { 63 | public string ZipCode { get; set; } 64 | } 65 | 66 | var autoCopy = AutoCopy.CreateMap(); 67 | 68 | autoCopy.Register(); 69 | 70 | Address a=new Address { ZipCode="1234567890"; }; 71 | 72 | Address b=autoCopy.Map(a); 73 | 74 | ``` 75 | 76 | ### 示例2 不同类型对象拷贝 77 | 78 | ```csharp 79 | 80 | public class Address 81 | { 82 | public string ZipCode { get; set; } 83 | } 84 | 85 | public class Telephone 86 | { 87 | public string Number { get; set; } 88 | } 89 | 90 | public class Customer 91 | { 92 | public Address Address { get; set; } 93 | public Telephone Phone { get; set; } 94 | public string Memo { get; set; } 95 | } 96 | 97 | public class CustomerInfo 98 | { 99 | public string zipCode { get; set; } 100 | public string PhoneNumber { get; set; } 101 | public string Memo { get; set; } 102 | } 103 | 104 | var autoCopy = AutoCopy.CreateMap(); 105 | 106 | autoCopy 107 | .ForMember(p => p.zipCode, opt => opt.MapFrom(p => p.Address.ZipCode)) 108 | .ForMember(p => p.PhoneNumber, opt => opt.MapFrom(p => p.Phone.Number)); 109 | 110 | autoCopy.Register(); 111 | 112 | Customer customer = new Customer(); 113 | 114 | customer.Address = new Address { ZipCode = "1234567890" }; 115 | 116 | customer.Phone = new Telephone { Number = "17791704580" }; 117 | 118 | customer.Memo = "Test"; 119 | 120 | CustomerInfo info = autoCopy.Map(customer); 121 | 122 | ``` 123 | 124 | ### 示例3 多AutoCopy示例嵌套 125 | 126 | ```csharp 127 | 128 | public class Data 129 | { 130 | public int width { get; set; } 131 | public int height { get; set; } 132 | public string ua { get; set; } 133 | public string ip { get; set; } 134 | public string imei { get; set; } 135 | public string android_id { get; set; } 136 | public string make { get; set; } 137 | public string model { get; set; } 138 | public string os { get; set; } 139 | public string osv { get; set; } 140 | public int connectionType { get; set; } 141 | public int deviceType { get; set; } 142 | public string mac { get; set; } 143 | public int screenWidth { get; set; } 144 | public int screenHeight { get; set; } 145 | public string appName { get; set; } 146 | public int ppi { get; set; } 147 | public string dpidsha1 { get; set; } 148 | public string plmn { get; set; } 149 | public string orientation { get; set; } 150 | public int pos { get; set; } 151 | public bool instl { get; set; } 152 | public string ver { get; set; } 153 | public string bundle { get; set; } 154 | public Ext ext { get; set; } 155 | } 156 | public class Ext 157 | { 158 | public int ID { get; set; } 159 | } 160 | 161 | string surl = "id=10010&width=10&height=10&ua=ua&ip=127.0.0.1&imei=00000000000000&android_id=A00000000000000&make=1111111111&model=XXX&os=android&osv=4.0.1&connectionType=1&deviceType=1&mac=0.0.0.0.0.0.0&screenWidth=100&screenHeight=100&appName=test&ppi=600&dpidsha1=dpidsha1&plmn=1&orientation=1&pos=1&instl=true&ver=1.0.0&bundle=bundle"; 162 | 163 | HttpQueryCollection collection = new HttpQueryCollection(surl, false); 164 | 165 | var ac = AutoCopy.CreateMap(); 166 | 167 | ac.Provider= new HttpRequestParamsExpressionProvider(typeof(NameValueCollection)); 168 | 169 | var autoCopy = AutoCopy.CreateMap(); 170 | 171 | autoCopy.ForMember(p => p.ext, opt => opt.MapFrom(p=>ac.Map(p))); 172 | 173 | autoCopy.Provider = new HttpRequestParamsExpressionProvider(typeof(NameValueCollection)); 174 | 175 | autoCopy.Register(); 176 | 177 | Data data=autoCopy.Map(collection); 178 | 179 | ``` 180 | ## 类型转换 181 | ### 自动转换 182 | 内部类[TypeConverter](/AutoCopyLib/TypeConverter.cs)的TryConvert方法通过以下顺序进行类型的自动转换: 183 | 184 | 1. 是否存在显式转换操作符 185 | 2. 是否存在隐式转换操作符 186 | 3. 是否存在继承关系 187 | 4. 是否存在Convert.ToXXX方法 188 | 5. 是否可以调用目标类型上的TryParse方法 189 | 6. 调用[Convert.ChangeType](https://msdn.microsoft.com/en-us/library/system.convert.changetype(v=vs.110).aspx "Convert.ChangeType")方法 190 | ### 手动转换 191 | 192 | 通过调用**AutoCopy**类实例的**ForTypeConvert**方法来注册类型转换。 193 | 194 | ## 抽象类[TargetExpressionProviderBase](/AutoCopyLib/TargetExpressionProviderBase.cs)的TryGetExpression方法参数说明 195 | 196 | 假定AutoCopy中T1为源类型,T2为目标类型 197 | 198 | | | 属性名 | 备注 199 | ---|---|--- 200 | 1 | name | 目标属性名称 201 | 2 | parameter | 源类型的参数表达式 202 | 3 | destType | 目标类型 203 | 4 | exp | 通过TryGetExpression方法最后生成的表达式 204 | 5 | variable | 临时变量 205 | 6 | test | 测试表达式 206 | 7 | ifTrue | 是否需要测试;如果该值为true,则只有test执行返回true时才会继续执行exp 207 | 208 | ## 修改日志 209 | 2017-12-05 增加DataRow映射到实体类的示例程序 210 | 2017-12-13 调整了AutoCopy<,>类的参数顺序并且修改了Option.ResolveUsing方法参数类型错误的bug 211 | 2017-12-26 增加CopyMapAttribute特性来支持目标类型属性的别名映射 212 | 2017-12-27 增加CopyRequiredAttribute特性来支持检测目标类型属性所需要映射的值是否为空 **[需要进一步测试]** 213 | 2017-12-28 当Option.MapFrom函数中调用其他AutoCopy实例时从Decompiler函数中获取新的LambdaExpression 214 | 2018-01-12 重载Option.MapForm函数,添加一个字符串参数,指示目标的属性名称或映射名称 215 | 2018-02-09 修复bug:当将CopyRequired特性应用于需要AutoCopy实例嵌套映射的属性时,调用ConditionFalseRewriter类的Visit函数将导致错误 216 | ## 注意事项 217 | 218 | 由于AutoCopy在运行时通过主动调用**Register**方法使用反射分析类的属性,所以如果方法进行了混淆可能会出现Bug。 219 | -------------------------------------------------------------------------------- /Web.Test/App_Code/AutoCopyUtils.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Specialized; 2 | using System.Web; 3 | using AgileObjects.ReadableExpressions.Extensions; 4 | using AgileObjects.ReadableExpressions; 5 | /// 6 | /// AutoCopyUtils 的摘要说明 7 | /// 8 | public class AutoCopyUtils 9 | { 10 | private static AutoCopyLib.AutoCopy autoCopy = null; 11 | public static void Initialize() 12 | { 13 | autoCopy = AutoCopyLib.AutoCopy.CreateMap(); 14 | autoCopy.Provider = new HttpRequestParamsExpressionProvider(typeof(NameValueCollection)); 15 | autoCopy.Register(true); 16 | } 17 | public static AutoCopyLib.AutoCopy Instance 18 | { 19 | get 20 | { 21 | return autoCopy; 22 | } 23 | } 24 | public static string LambdaExpressionString 25 | { 26 | get 27 | { 28 | return autoCopy.Lambda.ToReadableString(); 29 | } 30 | } 31 | } -------------------------------------------------------------------------------- /Web.Test/App_Code/Data.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Web; 5 | 6 | /// 7 | /// Data 的摘要说明 8 | /// 9 | public class Data 10 | { 11 | public int width { get; set; } 12 | public int height { get; set; } 13 | public string ua { get; set; } 14 | public string ip { get; set; } 15 | public string imei { get; set; } 16 | public string android_id { get; set; } 17 | public string make { get; set; } 18 | public string model { get; set; } 19 | public string os { get; set; } 20 | public string osv { get; set; } 21 | public int connectionType { get; set; } 22 | public int deviceType { get; set; } 23 | public string mac { get; set; } 24 | public int screenWidth { get; set; } 25 | public int screenHeight { get; set; } 26 | public string appName { get; set; } 27 | public int ppi { get; set; } 28 | public string dpidsha1 { get; set; } 29 | public string plmn { get; set; } 30 | public string orientation { get; set; } 31 | public int pos { get; set; } 32 | public bool instl { get; set; } 33 | public string ver { get; set; } 34 | public string bundle { get; set; } 35 | } -------------------------------------------------------------------------------- /Web.Test/App_Code/HttpRequestParamsExpressionProvider.cs: -------------------------------------------------------------------------------- 1 | using AutoCopyLib; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | using System.Text; 6 | using System.Threading.Tasks; 7 | using System.Linq.Expressions; 8 | using System.Collections.Specialized; 9 | using System.Reflection; 10 | 11 | internal class HttpRequestParamsExpressionProvider : TargetExpressionProviderBase 12 | { 13 | public HttpRequestParamsExpressionProvider(Type targetType) : base(targetType) 14 | { 15 | if (!typeof(NameValueCollection).IsAssignableFrom(targetType)) 16 | { 17 | throw new ArgumentException(string.Format("{0}不是有效的NameValueCollection派生类", targetType.Name)); 18 | } 19 | } 20 | private MethodInfo isNullOrEmpty = typeof(string).GetMethod("IsNullOrEmpty"); 21 | 22 | public override bool TryGetExpression(string name, ParameterExpression parameter, Type destType, out Expression exp, out ParameterExpression variable, out Expression test, out bool ifTrue) 23 | { 24 | exp = null; 25 | test = null; 26 | variable = null; 27 | ifTrue = false; 28 | try 29 | { 30 | exp = Expression.Property(parameter, "Item", Expression.Constant(name, typeof(string))); 31 | if(destType==typeof(string)) 32 | { 33 | test = Expression.Not(Expression.Call(null, isNullOrEmpty, exp)); 34 | ifTrue = true; 35 | } 36 | return true; 37 | } 38 | catch 39 | { 40 | return false; 41 | } 42 | 43 | } 44 | } -------------------------------------------------------------------------------- /Web.Test/Global.asax: -------------------------------------------------------------------------------- 1 | <%@ Application Language="C#" %> 2 | 3 | 39 | -------------------------------------------------------------------------------- /Web.Test/Handler.ashx: -------------------------------------------------------------------------------- 1 | <%@ WebHandler Language="C#" Class="Handler" %> 2 | 3 | using System; 4 | using System.Web; 5 | 6 | public class Handler : IHttpHandler { 7 | 8 | public void ProcessRequest (HttpContext context) { 9 | context.Response.ContentType = "text/plain"; 10 | var data=AutoCopyUtils.Instance.Map(context.Request.Params); 11 | context.Response.Write("lambda表达式为:" + AutoCopyUtils.LambdaExpressionString); 12 | if(data==null) 13 | { 14 | context.Response.Write("没有接收到数据"); 15 | } 16 | else 17 | { 18 | context.Response.Write(Newtonsoft.Json.JsonConvert.SerializeObject(data)); 19 | } 20 | } 21 | 22 | public bool IsReusable { 23 | get { 24 | return false; 25 | } 26 | } 27 | } -------------------------------------------------------------------------------- /Web.Test/Web.Debug.config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 17 | 18 | 19 | 31 | 32 | -------------------------------------------------------------------------------- /Web.Test/Web.config: -------------------------------------------------------------------------------- 1 |  2 | 6 | 7 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | -------------------------------------------------------------------------------- /Web.Test/packages.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 7 | --------------------------------------------------------------------------------