【发布时间】:2013-09-20 15:58:41
【问题描述】:
首先,我将描述我想要实现的目标。
我想创建一个方法来获取属性名称及其值以用于日志记录,所以我有这个:
public void Log<TPropertySource, TProperty>(Expression<Func<TPropertySource, object>> property, TProperty initialValue, TProperty changedValue){...}
现在这需要我指定属性的类型,即 .. meh,因为理论上我可以从表达式中提取它;然而,表达式需要返回一个对象以适应该属性可能具有的所有可能类型。
我正在考虑仅对 BCL 最常用的值类型进行重载,并为其他所有内容使用对象重载,例如
public void Log<TPropertySource>(Expression<Func<TPropertySource, string>> property, string initialValue, string changedValue){...}
public void Log<TPropertySource>(Expression<Func<TPropertySource, int>> property, int initialValue, int changedValue){...}
但这也不理想,因为我最终会遇到十几个重载
所以基本上我想知道是否有更好(更懒惰)的方法来做到这一点?
还有一个问题:为什么我在 Log
【问题讨论】:
-
类型推断应该推断两种类型。
-
我不明白,为什么你不能有
public void Log<TPropertySource, TProperty>(Expression<Func<TPropertySource, TProperty>> property, TProperty initialValue, TProperty changedValue)?您说“表达式需要返回一个对象以适应该属性可以具有的所有可能类型”,但是对于TProperty可以采用的类型没有限制,因此所有属性类型都应该有效。 -
@SLaks 会很好,但事实并非如此。至少,我无法让它工作。
-
@hvd 我可以,但我必须像 Log
(x=>x.Name, "Bob", "Bill");我试图避免必须指定第二个通用参数(在这种情况下为字符串)。 -
@Eugene 更改 API 可以吗?
logger.Property<A>(x => x.Age).Log(1, 2);应该是可行的。
标签: c# expression-trees