我如何才能创建一个具有smiliar功能的方法作为新的“”";操作人员
本文关键字:方法 操作 quot 功能 smiliar 创建 一个 | 更新日期: 2023-09-27 18:29:08
使用C#6,我们可以使用新的?
来访问属性和方法,而无需对每个属性和方法进行null检查。是否可以使用表达式编写一个具有siliar函数的方法?
例如,我必须使用一个奇怪的对象结构(它来自我们无法更改的第三方库)。访问某些属性通常需要长的点链:
rootObject.Services.First().Segments.First().AnotherCollection.First().Weight;
在rootObject
之后的任何对象都可以是null
。我宁愿不在它周围放一个try/catch
。另外,单独检查每个属性也是一项艰巨的工作。所以我想知道是否可以将它传递给采用表达式的方法,遍历每个属性并在那里检查其值:
var value = PropertyHelper.GetValue(() => rootObject.Services.First().Segments.First().AnotherCollection.First().Weight);
我想它的签名应该是这样的:
public static T GetValue<T>(Expression<Func<T>> expression)
{
// analyze the expression and evaluate each property/method
// stop when null or return the value
}
我真的不确定表达式是否能够实现我要做的事情,在我开始实验之前,我想问一下这是否可能。
void Main()
{
var foo = new Foo();
var qux = NullPropertyExtension.GetValue(() => foo.Bar.Qux);
Console.WriteLine(qux);
}
public class Foo
{
public Foo Bar { get; set; }
public string Qux {get;set;}
}
// Define other methods and classes here
public static class NullPropertyExtension
{
public static TValue GetValue<TValue>(Expression<Func<TValue>> property)
{
var visitor = new Visitor();
var expression = visitor.Visit(property.Body);
var lambda = Expression.Lambda<Func<TValue>>(expression);
var func = lambda.Compile();
return func();
}
private class Visitor : System.Linq.Expressions.ExpressionVisitor
{
protected override Expression VisitMember(MemberExpression node)
{
var isNotNull = Expression.NotEqual(node.Expression, Expression.Constant(null));
return Expression.Condition(
isNotNull,
node,
Expression.Constant(null, node.Type));
}
}
}