考虑以下方法:如何使用表达式设置属性值?
public static void SetPropertyValue(object target, string propName, object value)
{
var propInfo = target.GetType().GetProperty(propName,
BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly);
if (propInfo == null)
throw new ArgumentOutOfRangeException("propName", "Property not found on target");
else
propInfo.SetValue(target, value, null);
}
你会如何去写它的表达能等同,而不需要为目标的额外的参数传递?
为什么不直接设置属性我可以听到你说。例如,假设我们有以下的类有一个公共的getter但私人二传手属性:
public class Customer
{
public string Title {get; private set;}
public string Name {get; set;}
}
我想能够调用:
var myCustomerInstance = new Customer();
SetPropertyValue<Customer>(cust => myCustomerInstance.Title, "Mr");
现在这里是一些示例代码。
public static void SetPropertyValue<T>(Expression<Func<T, Object>> memberLamda , object value)
{
MemberExpression memberSelectorExpression;
var selectorExpression = memberLamda.Body;
var castExpression = selectorExpression as UnaryExpression;
if (castExpression != null)
memberSelectorExpression = castExpression.Operand as MemberExpression;
else
memberSelectorExpression = memberLamda.Body as MemberExpression;
// How do I get the value of myCustomerInstance so that I can invoke SetValue passing it in as a param? Is it possible
}
任何指针?
你为什么要这么做?如果该物业拥有私人二传手,那么它并不意味着从物体外面改变!您提议的功能会破坏程序的语义。 – 2012-03-07 12:56:41
@VladislavZorov我可以看到这样的评论,我分享你的看法。在这种情况下,第三方DTO需要在单元测试中启动,这将是最简单的方法。反思也有其用处。 – Anastasiosyal 2012-03-07 13:03:18
可能的重复[如何设置值属性选择器表达式>](http://stackoverflow.com/questions/8107134/how-set-value-a-property-selector-expressionfunct-tresult)http:// stackoverflow.com/questions/5075484/property-selector-expressionfunct-how-to-get-set-value-to-selected-property –
nawfal
2013-04-17 20:43:32