您的位置:首页 > 编程语言 > C#

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.



内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: