如何使用lambda表达式和匿名类型获取类型的属性名称?

编程入门 行业动态 更新时间:2024-10-15 10:18:05
本文介绍了如何使用lambda表达式和匿名类型获取类型的属性名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试使用表达式树和匿名类型来实现以下目标.

I am trying to use Expression Trees and anonymous types to achieve the following.

让我说我上了这个课:

class Person { public string FirstName {get;set;} public string MiddleName {get;set;} public string LastName {get;set;} public DateTime DateOfBirth {get;set;} }

现在我希望能够拨打以下电话:

Now I want to be able to call the following:

string[] names = Foo<Person>(x=> new { x.LastName, x.DateOfBirth });

我希望名称包含"LastName"和"DateOfBirth"两个项目.

I want names to contain 2 items, "LastName" and "DateOfBirth".

我试图以一种编译时安全的方式扩展 PetaPoco ,而不是编写字符串sql,这样我就可以指定要包含在SQL中的属性/列的列表,而不是选择所有内容.我有一些相当大的实体,在某些情况下,出于性能原因,我不想选择所有列.

I am trying to extend PetaPoco, in a compile time safe way rather than writing string sql, so that I can specify a list of properties/columns I want to include in the SQL, rather than it selecting everything. I have some pretty large entities and there are cases where I do not want to select all the columns for performance reasons.

推荐答案

我很懒,因此此代码仅处理公共属性.但这应该是入门的良好基础.

I'm lazy so this code handles only public properties. But it should be a good base to get you started.

public static string[] Foo<T>(Expression<Func<T, object>> func) { var properties = func.Body.Type.GetProperties(); return typeof(T).GetProperties() .Where(p => properties.Any(x => p.Name == x.Name)) .Select(p => { var attr = (ColumnAttribute) p.GetCustomAttributes(typeof(ColumnAttribute), true).FirstOrDefault(); return (attr != null ? attr.Name : p.Name); }).ToArray(); }

更多推荐

如何使用lambda表达式和匿名类型获取类型的属性名称?

本文发布于:2023-11-07 00:38:44,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1565079.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:类型   表达式   如何使用   属性   名称

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!