我可以使用.ToString().IsNullOrEmpty() 在 StringBuilder 对象上


 /*Class definition*/
public class ConcreteClassModel : BaseModel
{
...
public bool IntersectsWith(ConcreteClassModel ccm)
    {
        ccm.StartDateDT = DateTime.Parse(ccm.StartDate);
        ccm.EndDateDT = DateTime.Parse(ccm.EndDate);
        this.StartDateDT = DateTime.Parse(this.StartDate);
        this.EndDateDT = DateTime.Parse(this.EndDate);
        return !(this.StartDateDT > ccm.EndDateDT || this.EndDateDT < ccm.StartDateDT);
    }
}
/*Inside Controller Method*/
List<ConcreteClassModel> periods = LoadAllByParameters<ConcreteClassModel>(
            ccm.CoverId, x => x.CoverId,
            ccm.SectionId, x => x.SectionId);
var intersectingPeriods =
            periods.Where(x => x.IntersectsWith(ccm));
StringBuilder partReply = intersectingPeriods.Aggregate(new StringBuilder(), (a, b) => a.Append(b));
********if (!partReply.ToString().IsNullOrEmpty())***************************
        {
            string reply =
                "<div id='duplicateErrorDialog' title='Duplication Error'><span> Duplicate Period(s)</br>" +
                partReply + "</span></ div >";
            return Json(reply, JsonRequestBehavior.AllowGet);
        }    
return Json(null, JsonRequestBehavior.AllowGet);

以上似乎工作正常,如果没有找到重复的日期周期,空响应将触发我的 javascript 保存。 但是可以使用: if (!partReply.ToString().IsNullOrEmpty())由于StringBuilder没有自己的.IsNullOrEmpty() 等效?我能找到的每个评论、问题等都只与字符串有关,在 MSDN 上看不到任何内容!

在您的情况下,partReply永远不能为 null 或空,因为当没有输入元素时Enumerable.Aggregate抛出InvalidOperationException您的代码崩溃了。

在一般情况下,您可以将 Length 属性与 0 进行比较,例如:

if (partReply.Length > 0)

您可以创建一个快速方法来帮助检查StringBuilder对象是 null 还是空:

private bool IsStringBuilderNullOrEmpty(StringBuilder sb) {
    return sb == null || sb.Length == 0);
}
//text examples
StringBuilder test = null;
Console.WriteLine(IsStringBuilderNullOrEmpty(test));//true

StringBuilder test = new StringBuilder();
test.Append("");
Console.WriteLine(IsStringBuilderNullOrEmpty(test));//true
StringBuilder test = new StringBuilder();
test.Append("hello there");
Console.WriteLine(IsStringBuilderNullOrEmpty(test));//false

最新更新