-
-
Save darrencauthon/6154558ad5c9f9df7c669fb9abee658f to your computer and use it in GitHub Desktop.
Example of Dynamic Proxy ViewModel in C#?
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; | |
namespace VMSandbox | |
{ | |
class AModel | |
{ | |
public DateTime Date { get; set; } = DateTime.UtcNow; | |
public int MyLifeForTheCodeDownloads { get; set; } = Int32.MaxValue; | |
} | |
} |
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; | |
namespace VMSandbox | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
var model = new AModel { Date = DateTime.Now, MyLifeForTheCodeDownloads = 7 }; | |
dynamic plain = new ViewModelBase(model); | |
Console.WriteLine(plain.Date); // 6/2/2016 11:52:05 PM | |
Console.WriteLine(plain.MyLifeForTheCodeDownloads); // 7 | |
dynamic special = new SpecialViewModel(model); | |
Console.WriteLine(special.Date); // 6/2/2016 | |
Console.WriteLine(special.MyLifeForTheCodeDownloads); // 7 | |
} | |
} | |
} |
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
namespace VMSandbox | |
{ | |
class SpecialViewModel : ViewModelBase | |
{ | |
public SpecialViewModel(object subject) : base(subject) {} | |
public string Date | |
{ | |
get { return TheSubject.Date.ToShortDateString(); } | |
} | |
} | |
} |
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.Dynamic; | |
namespace VMSandbox | |
{ | |
public class ViewModelBase : DynamicObject | |
{ | |
public dynamic TheSubject { get; } | |
public ViewModelBase(dynamic subject) | |
{ | |
TheSubject = subject; | |
} | |
public override bool TryGetMember(GetMemberBinder binder, out object result) | |
{ | |
result = null; | |
var property = TheSubject.GetType().GetProperty(binder.Name); | |
if (property == null) | |
return false; | |
result = property.GetValue(TheSubject).ToString(); | |
return true; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment