0
 /*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()) As StringBuilder 没有自己的 .IsNullOrEmpty() 等价物吗?我能找到的每条评论、问题等都只与字符串有关,在 MSDN 上看不到任何东西!

4

2 回答 2

2

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

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

if (partReply.Length > 0)
于 2016-02-11T16:53:25.063 回答
0

您可以创建一个快速方法来帮助检查您的StringBuilder对象是否为空或为空:

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
于 2016-02-11T16:38:47.433 回答