你可以嘗試表達樹做「魔術」的東西。 例如:
class BaseEntity
{
}
class MessageList : BaseEntity
{
}
class Application:BaseEntity
{
public List<BaseEntity> MessageLists { get; set; }
public Application()
{
MessageLists = new List<BaseEntity>();
}
}
class ExpressionHelper
{
public static Action<object,object> GetMethod(string targetTypename,string targetMemberName,string sourceTypeName)
{
ParameterExpression targetExpression = Expression.Parameter(typeof(object));
MemberExpression propertyExpression = Expression.PropertyOrField(Expression.TypeAs(targetExpression, Type.GetType(targetTypename)), targetMemberName);
ParameterExpression sourceExpression = Expression.Parameter(typeof(object));
Expression callExpression = Expression.Call(propertyExpression, "Add", null, Expression.TypeAs(sourceExpression, Type.GetType(sourceTypeName)));
var lambda = Expression.Lambda<Action<object, object>>(callExpression, targetExpression, sourceExpression);
var method = lambda.Compile();
return method;
}
}
用法:
var app = new Application();
var messageList = new MessageList();
var magicMethod = ExpressionHelper.GetMethod(/*type*/"Application",/*name of Property-Storage*/"MessageLists",/*type of element to store*/"MessageList");
magicMethod(app, messageList);
//now app.MessageLists has one element
好極了,這工作完美。爲我節省了800行煩人的代碼! – MariWing 2012-08-17 08:52:40
很高興幫助你! – 2012-08-17 10:02:54