日期:2014-05-18 浏览次数:20950 次
?在工作中看到
using System;
using System.Collections.Generic;
using System.Reflection;
namespace XXX.Common
{
internal interface INamedMemberAccessor
{
object GetValue(object instance);
void SetValue(object instance, object newValue);
}
/// <summary>
/// Abstraction of the function of accessing member of a object at runtime.
/// </summary>
public interface IMemberAccessor
{
/// <summary>
/// Get the member value of an object.
/// </summary>
/// <param name="instance">The object to get the member value from.</param>
/// <param name="memberName">The member name, could be the name of a property of field. Must be public member.</param>
/// <returns>The member value</returns>
object GetValue(object instance, string memberName);
/// <summary>
/// Set the member value of an object.
/// </summary>
/// <param name="instance">The object to get the member value from.</param>
/// <param name="memberName">The member name, could be the name of a property of field. Must be public member.</param>
/// <param name="newValue">The new value of the property for the object instance.</param>
void SetValue(object instance, string memberName, object newValue);
}
internal class PropertyAccessor<T, P> : INamedMemberAccessor
{
private Func<T, P> m_GetValueDelegate;
private Action<T, P> m_SetValueDelegate;
public PropertyAccessor(PropertyInfo propertyInfo)
{
Guard.ArgumentNotNull(propertyInfo, "Property can't be null");
var getMethodInfo = propertyInfo.GetGetMethod();
if (null != getMethodInfo)
{
m_GetValueDelegate = (Func<T, P>)Delegate.CreateDelegate(typeof(Func<T, P>), getMethodInfo);
}
var setMethodInfo = propertyInfo.GetSetMethod();
if (null != setMethodInfo)
{
m_SetValueDelegate = (Action<T, P>)Delegate.CreateDelegate(typeof(Action<T, P>), setMethodInfo);
}
}
public object GetValue(object instance)
{
Guard.ArgumentNotNull(m_GetValueDelegate, "The Property doesn't have GetMethod");
return m_GetValueDelegate((T)instance);
}
public void SetValue(object instance, object newValue)
{
Guard.ArgumentNotNull(m_SetValueDelegate, "The Property doesn't have SetMethod");
m_SetValueDelegate((T)instance, (P)newValue);