【发布时间】:2012-03-24 23:51:54
【问题描述】:
给定以下方法:
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 但私有 setter 的属性的类:
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
}
有什么建议吗?
【问题讨论】:
-
您为什么要这样做?如果属性有一个私有设置器,那么它并不意味着从对象外部更改!您提出的功能破坏了程序的语义。
-
@VladislavZorov 我可以看到这样的评论,我同意你的观点。在这种情况下,需要在单元测试中启动第三方 DTO,这将是最简单的方法。反射也有它的用途。
标签: c# linq expression