定义通用的可通过lambda表达式树来获取属性信息
Posted 石涛涛
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了定义通用的可通过lambda表达式树来获取属性信息相关的知识,希望对你有一定的参考价值。
/// <summary>
/// 获取指定属性信息(非String类型存在装箱与拆箱)
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="select"></param>
/// <returns></returns>
public
static
PropertyInfo GetPropertyInfo<T>(Expression<Func<T,dynamic>>
select
)
{
var
body =
select
.Body;
if
(body.NodeType == ExpressionType.Convert)
{
var
o = (body
as
UnaryExpression).Operand;
return
(o
as
MemberExpression).Member
as
PropertyInfo;
}
else
if
(body.NodeType == ExpressionType.MemberAccess)
{
return
(body
as
MemberExpression).Member
as
PropertyInfo;
}
return
null
;
}
/// <summary>
/// 获取指定属性信息(需要明确指定属性类型,但不存在装箱与拆箱)
/// </summary>
/// <typeparam name="T"></typeparam>
/// <typeparam name="TR"></typeparam>
/// <param name="select"></param>
/// <returns></returns>
public
static
PropertyInfo GetPropertyInfo<T, TR>(Expression<Func<T, TR>>
select
)
{
var
body =
select
.Body;
if
(body.NodeType == ExpressionType.Convert)
{
var
o = (body
as
UnaryExpression).Operand;
return
(o
as
MemberExpression).Member
as
PropertyInfo;
}
else
if
(body.NodeType == ExpressionType.MemberAccess)
{
return
(body
as
MemberExpression).Member
as
PropertyInfo;
}
return
null
;
}
/// <summary>
/// 获取类型的所有属性信息
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="select"></param>
/// <returns></returns>
public
static
PropertyInfo[] GetPropertyInfos<T>(Expression<Func<T,dynamic>>
select
)
{
var
body =
select
.Body;
if
(body.NodeType == ExpressionType.Parameter)
{
return
(body
as
ParameterExpression).Type.GetProperties();
}
else
if
(body.NodeType==ExpressionType.New)
{
return
(body
as
NewExpression).Members.Select(m => m
as
PropertyInfo).ToArray();
}
return
null
;
}
以上是关于定义通用的可通过lambda表达式树来获取属性信息的主要内容,如果未能解决你的问题,请参考以下文章
csharp C#使用Lambda表达式为动态类型和动态属性排序通用列表
漏洞扫描设备检测出服务存在漏洞:可通过HTTPS获取远端WWW服务版信息,如何解决?