在调用之前,请检查 Func 委托中的 T 是否为空
本文关键字:是否 string 调用 检查 Func | 更新日期: 2023-09-27 17:57:16
我正在尝试弄清楚如何在调用对象之前检查对象是否为空。下面是一些示例代码:
public class NotifyTemplate<T> where T : class
{
public Func<T, string> Value { get; set; }
public string Key { get; set; }
}
public class User
{
public int Id { get; set; }
public string UserName { get; set; }
public Contact Contact { get; set; }
}
public class Contact
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
我想在实际调用委托之前检查我尝试调用的任何对象是否为 null。我可以尝试接球,但这似乎矫枉过正。这是我的用法示例:
var notifyList = new List<NotifyTemplate<User>>()
{
new NotifyTemplate<User>()
{
Value = u => u.Contact.FirstName,
Key = "FName"
},
new NotifyTemplate<User>()
{
Value = u => u.UserName,
Key = "UserName"
}
};
var user = new User()
{
Id = 1,
UserName = "ddivita@dd.com",
};
foreach (var notifyTemplate in notifyList)
{
//This is where I want to check if the value is null or not before I invoke.
var name = notifyTemplate.Value.Invoke(user);
}
如您所见,Contact 对象为 null,未在 new User
声明中初始化。因此,在 foreach
语句中,我想检查 Value 属性,并在调用委托中的对象之前查看它是否为 null。
重点是我们正在设置一个通知系统,为了使开发人员更容易,Func 将用于替换通知模板中的键。
以下是 temaplte 的外观:
<html>
<body>
Hello There [FName] [LName]. Thank you for signing up using the username: [UserName].
</body>
</html>
开发人员会将他们要使用的模板和通知模板列表传递给我们的通知服务
如果由于某种原因联系信息未正确保存,并且我们从数据库中提取 User 对象,则假设 Contact 对象为 null。我们需要在调用 invoke 以获取值之前评估 Contact 对象是否为 null。
你可以在lambda中这样做:
Value = u => u.Contact != null ? u.Contact.FirstName : string.Empty
正如Neolisk所建议的那样,我正在这样做:
foreach (var notifyTemplate in notifyList)
{
var value = string.Empty;
try
{
value = notifyTemplate.Value.Invoke(user);
}
catch (Exception ex)
{
//log error
}
var theVlaue = value;
}