Created
January 29, 2015 13:05
-
-
Save alexanderfast/f5397c803b004e3293de to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Reflection; | |
using Changelog.Annotations; | |
using Changelog.Properties; | |
namespace Namespace | |
{ | |
public class SettingsViewModelBase : ViewModelBase, ICloneable | |
{ | |
public void Load() | |
{ | |
Load(Settings.Default); | |
} | |
internal void Load([NotNull] Settings settings) | |
{ | |
CopyProperties(settings, this); | |
} | |
public void Save() | |
{ | |
Save(Settings.Default); | |
} | |
internal void Save([NotNull] Settings settings) | |
{ | |
CopyProperties(this, settings); | |
} | |
public virtual object Clone() | |
{ | |
var target = Activator.CreateInstance(GetType()); | |
CopyProperties(this, target); | |
return target; | |
} | |
private static void CopyProperties(object source, object target) | |
{ | |
var sourceProperties = source.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.GetProperty); | |
var targetProperties = target.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.SetProperty); | |
foreach (var sourceProperty in sourceProperties) | |
{ | |
foreach (var targetProperty in targetProperties) | |
{ | |
if (targetProperty.Name != sourceProperty.Name) | |
continue; | |
if (targetProperty.PropertyType != sourceProperty.PropertyType) | |
throw new InvalidOperationException(); | |
var value = sourceProperty.GetValue(source, null); | |
targetProperty.SetValue(target, value, null); | |
break; | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment