添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
相关文章推荐
失恋的马铃薯  ·  python ...·  7 月前    · 
害羞的小熊猫  ·  Java 8 升Java 11 ...·  8 月前    · 

From time to time I’m dealing with API that’s using Expression > as parameter, mainly to show property you want to deal with. And that’s fine, if you need just the expression itself. But I often create my custom extensions, where I’m somehow working with the property itself or the result. And that’s a problem, because I don’t know any info about the type, it’s just object.

If you try to directly cast the expression, it will not work, of course. First I though, it’s going to be a lot of juggle with pieces of expression and reconstructing the final one. But it’s pretty easy, see yourself:

void FooBar<TEntity, TProperty>(TEntity entity, Expression<Func<TEntity, TProperty>> property)
	Expression<Func<TEntity, object>> result;
	if (typeof(TProperty).IsValueType)
		result =  Expression.Lambda<Func<TEntity, object>>(Expression.Convert(property.Body, typeof(object)), property.Parameters);
		result = Expression.Lambda<Func<TEntity, object>>(property.Body, property.Parameters);
	// do something with result ...

I’m simply creating new expression based on the original ones’ body and parameters. If the TProperty’s type was value type I only do boxing in addition.

Nothing difficult, right?

Jiří Činčura is .NET, C# and Firebird expert. He focuses on data and business layers, language constructs, parallelism, databases and performance. For almost two decades he contributes to open-source, i.e. FirebirdClient. He works as a senior software engineer for Microsoft. Frequent speaker and blogger at www.tabsoverspaces.com.