gpt4 book ai didi

c# - 如何解压表达式树并检查空值

转载 作者:行者123 更新时间:2023-11-30 17:48:32 24 4
gpt4 key购买 nike

引用下面的 2 个类,我经常编写这样的 LINQ 语句..

using (var db = new DBContext())
{
var result = db.Countries
.Select(c => new
{
c.Name,
c.Leader != null ? c.Leader.Title : String.Empty,
c.Leader != null ? c.Leader.Firstname : String.Empty,
c.Leader != null ? c.Leader.Lastname : String.Empty
});
}

public class Country
{
public int Id { get; set; }
public string Name { get; set; }
public Leader Leader { get; set; }
}

public class Leader
{
public string Title { get; set; }
public string Firstname { get; set; }
public string Lastname { get; set; }
}

我的问题是我不得不不断地重复我对子导航属性的空检查,我想知道是否有一种方法可以使用某种表达式树动态提取属性值,同时检查空值以及它们是否不存在发送回一个空字符串,类似于下面的方法..

public class Country
{
// Properties //

public string SafeGet(Expression<Func<Country, string>> fnc)
{
// Unpack fnc and check for null on each property?????
}

}

用法:

using (var db = new DBContext())
{
var result = db.Countries
.Select(c => new
{
c.Name,
c.SafeGet(l => l.Leader.Title),
c.SafeGet(l => l.Leader.Firstname),
c.SafeGet(l => l.Leader.Lastname)
});
}

如果有人能提供一个基本示例,那会很棒,因为除了创建它们之外,我对表达式树没有太多经验。

谢谢。

更新 -> 会像下面这样工作吗?

public string GetSafe(Expression<Func<Country, string>> fnc)
{
var result = fnc.Compile().Invoke(this);
return result ?? string.Empty;
}

最佳答案

我认为不需要表达。我会简单地使用像

这样的扩展方法
    public static class ModelExtensions
{
// special case for string, because default(string) != string.empty
public static string SafeGet<T>(this T obj, Func<T, string> selector)
{
try {
return selector(obj) ?? string.Empty;
}
catch(Exception){
return string.Empty;
}
}
}

它适用于所有类,您可以进一步实现其他数据类型。用法和你一样。

关于c# - 如何解压表达式树并检查空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22959638/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com