RaUI/Source/ryControls/Sheng.Winform.Controls/Kernal/FastReflection/PropertyAccessor.cs
鑫Intel 8b41f58f5c ### 2021-07-01更新
------
#### ryControlsV4    V3.0.2107.0101
- *.[新增]新增Sheng.Winform.Controls部分控件。

#### RyWeb    V3.0.2107.0101
- *.[新增]QuickWeb新增引用页设置。
#### MyDbV4    V3.0.2107.0101
- *.[新增]支持忽略大小写的替换功能。
2021-07-04 09:41:31 +08:00

97 lines
2.8 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Expressions;
using System.Reflection;
namespace Sheng.Winform.Controls.Kernal
{
public interface IPropertyAccessor
{
object GetValue(object instance);
void SetValue(object instance, object value);
}
public class PropertyAccessor : IPropertyAccessor
{
private Func<object, object> m_getter;
private MethodInvoker m_setMethodInvoker;
public PropertyInfo PropertyInfo { get; private set; }
public PropertyAccessor(PropertyInfo propertyInfo)
{
this.PropertyInfo = propertyInfo;
this.InitializeGet(propertyInfo);
this.InitializeSet(propertyInfo);
}
private void InitializeGet(PropertyInfo propertyInfo)
{
if (!propertyInfo.CanRead) return;
// Target: (object)(((TInstance)instance).Property)
// preparing parameter, object type
var instance = Expression.Parameter(typeof(object), "instance");
// non-instance for static method, or ((TInstance)instance)
var instanceCast = propertyInfo.GetGetMethod(true).IsStatic ? null :
Expression.Convert(instance, propertyInfo.ReflectedType);
// ((TInstance)instance).Property
var propertyAccess = Expression.Property(instanceCast, propertyInfo);
// (object)(((TInstance)instance).Property)
var castPropertyValue = Expression.Convert(propertyAccess, typeof(object));
// Lambda expression
var lambda = Expression.Lambda<Func<object, object>>(castPropertyValue, instance);
this.m_getter = lambda.Compile();
}
private void InitializeSet(PropertyInfo propertyInfo)
{
if (!propertyInfo.CanWrite) return;
this.m_setMethodInvoker = new MethodInvoker(propertyInfo.GetSetMethod(true));
}
public object GetValue(object o)
{
if (this.m_getter == null)
{
throw new NotSupportedException("Get method is not defined for this property.");
}
return this.m_getter(o);
}
public void SetValue(object o, object value)
{
if (this.m_setMethodInvoker == null)
{
throw new NotSupportedException("Set method is not defined for this property.");
}
this.m_setMethodInvoker.Invoke(o, new object[] { value });
}
#region IPropertyAccessor Members
object IPropertyAccessor.GetValue(object instance)
{
return this.GetValue(instance);
}
void IPropertyAccessor.SetValue(object instance, object value)
{
this.SetValue(instance, value);
}
#endregion
}
}