C# 对象字符串合并

C# 对象字符串合并,c#,visual-studio-2010,sharepoint-2010,C#,Visual Studio 2010,Sharepoint 2010,你好 我正在尝试将coalesce与splistem结合使用。我想做的很简单。检查对象是否有值,如果为true,则将SPListItem字符串放入变量,如果为false,则将String.Empty放入变量 似乎联合不能做到这一点。我可以创建一个扩展方法来接受SPListItem并执行此操作吗? 到目前为止,我有: private static string Coalesce(Object historyListItem) { try { return histo

你好

我正在尝试将coalesce与splistem结合使用。我想做的很简单。检查对象是否有值,如果为true,则将SPListItem字符串放入变量,如果为false,则将String.Empty放入变量

似乎联合不能做到这一点。我可以创建一个扩展方法来接受SPListItem并执行此操作吗? 到目前为止,我有:

private static string Coalesce(Object historyListItem)
{
    try
    {
        return historyListItem.ToString();
    }
    catch (Exception ex)
    {
        return string.Empty;
    }
}

我认为这样做是不对的。关于如何修改的任何想法都要符合“Microsoft最佳实践”?

如果问题为空,您可以执行以下操作:

return historyListItem == null ? string.Empty : historyListItem.ToString();

“检查对象是否有值”的确切含义是什么?基本上,SPListItem可以包含文本,也可以不包含文本。我想检查它是否有一个值,那么您希望出现什么异常,以及从何处出现?这个问题很混乱…就像@JonSkeet说的…不太清楚。。。我能看到抛出异常的唯一地方是if
historyListItem
为null。在这种情况下,您实际上可以使用coalesce
??
选项。如果问题为null,您可以执行
返回historyListItem==null?string.Empty:historyListItem.ToString()