Dynamic in C# 4.0, Part 8
2009-09-16 14:35
441 查看
Demo Code static class DynamicHelper { public static dynamic AsDynamic(this T source) { return new DynamicReflection(source); } class DynamicReflection : DynamicObject { public DynamicReflection(T source) : base() { this.Source = source; } public override bool TrySetMember(SetMemberBinder binder, object value) { // find the member MemberInfo member; if (!TryFindMember(binder.Name, out member)) { return false; } // we can only set values to fields and properties // using reflection switch (member.MemberType) { /* todo: check the type of the incoming value and the type of the property. */ case (MemberTypes.Field): ((FieldInfo)member).SetValue(Source, value); return true; case (MemberTypes.Property): ((PropertyInfo)member).SetValue(Source, value,/*ndex*/ null); // we don't support indexed properties return true; } // didn't work return false; } public override bool TryGetMember(GetMemberBinder binder, out object result) { // find the member MemberInfo member; if (!TryFindMember(binder.Name, out member)) { result = null; return false; } // we can only set values to fields and properties // using reflection switch (member.MemberType) { /* todo: check the type of the incoming value and the type of the property. */ case (MemberTypes.Field): result = ((FieldInfo)member).GetValue(Source); return true; case (MemberTypes.Property): result = ((PropertyInfo)member).GetValue(Source,/*ndex*/ null); // we don't support indexed properties return true; } // didn't work result = null; return false; } private bool TryFindMember(string name, out MemberInfo memberInfo) { // find the member var members = Type.GetMember(name, MemberTypes.All, BindingFlags.IgnoreCase | BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public); // more than 1 not supported for now if (members.Length != 1) { memberInfo = null; return false; } memberInfo = members[0]; return true; } private Type Type { get { return typeof(T); } } public T Source { get; private set; } } }As always, happy coding. | ||
相关文章推荐
- Dynamic in C# 4.0, Part 7
- Dynamic in C# 4.0, Part 1
- Dynamic in C# 4.0, Part 5
- Dynamic in C# 4.0, Part 4
- Dynamic in C# 4.0, Part 6
- Dynamic in C# 4.0, Part 2
- Dynamic in C# 4.0, Part 3
- 基于Visual Studio2010与C#4.0新功能和展望--“dynamic”和“object”之间的关键区别
- Part Alerts Now in C#
- C# 4.0 Dynamic --通过DLR直接调用IronPython
- Socket Programming in C# - Part 2
- c# 4.0的dynamic和动态多分派
- C#4.0入门 第一章 dynamic类型—第一页 dynamic类型((转)
- Usage of keywords "in" and "out" in C#(.NET 4.0)
- C# Heap(ing) Vs Stack(ing) in .NET: Part III
- Philosophies Of Arguments Feature in C# 4.0
- C# 4.0 新特性dynamic、可选参数、命名参数等
- Part 48 to 51 Talking about Access Modifiers in C#
- Creating Types in C#(Chapter 3 of C# 4.0 in a nutshell)
- C# 4.0 特性: dynamic 和 ExpandoObject