c# – 从字符串创建属性选择器表达式

前端之家收集整理的这篇文章主要介绍了c# – 从字符串创建属性选择器表达式前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试从字符串生成属性选择器”.

让我用一个真实的例子来解释一下自己:

我们有一个Person类,其中包含Name(string)属性.

我可以像这个propertySelector一样手动创建一个“属性选择器”:

  1. Expression<Func<Person,string>> propertySelector = x => x.Name;

但我想用我的方法获得相同的属性选择器.

  1. var propertySelector = CreatePropertySelectorExpression<Person,string>("Name");

到目前为止我所拥有的是:

  1. public static Expression<Func<TIn,TOut>> CreatePropertySelectorExpression<TIn,TOut>(string path)
  2. {
  3. Expression exp = Expression.Parameter(typeof(TIn),"x");
  4. foreach (var property in path.Split('.'))
  5. {
  6. exp = Expression.PropertyOrField(exp,property);
  7. }
  8. return exp;
  9. }

但是……我得到了无效的施法错误

Cannot implicitly convert type ‘System.Linq.Expressions.Expression’ to
‘System.Linq.Expressions.Expression>’. An
explicit conversion exists (are you missing a cast?)

我对表达式很新,我不知道如何继续:(

解决方法

你的exp只包含lambda的主体.但是你想要一个实际的lambda函数,它接受一个类型为TIn的参数.所以你需要使用Expression.Lambda创建一个lambda:
  1. var param = Expression.Parameter(typeof(TIn));
  2. var body = Expression.PropertyOrField(param,propertyName);
  3. return Expression.Lambda<Func<TIn,TOut>>(body,param);

请注意,表达式并没有真正帮助你.您可能需要编译函数

  1. private static Func<TIn,TOut> CreatePropertyAccessor<TIn,TOut> (string propertyName)
  2. {
  3. var param = Expression.Parameter(typeof(TIn));
  4. var body = Expression.PropertyOrField(param,propertyName);
  5. return Expression.Lambda<Func<TIn,param).Compile();
  6. }

然后你可以像这样使用它:

  1. var name1 = CreatePropertyAccessor<Obj,string>("Name");
  2. var name2 = CreatePropertyAccessor<Obj,string>("Name2");
  3. var name3 = CreatePropertyAccessor<Obj,string>("Name3");
  4.  
  5. var o = new Obj() // Obj is a type with those three properties
  6. {
  7. Name = "foo",Name2 = "bar",Name3 = "baz"
  8. };
  9.  
  10. Console.WriteLine(name1(o)); // "foo"
  11. Console.WriteLine(name2(o)); // "bar"
  12. Console.WriteLine(name3(o)); // "baz"

猜你在找的C#相关文章