如果字符串与格式不匹配,如何在C#中抛出异常?

时间:2012-09-22 13:20:02

标签: c#

如果我在vm.TempRowKey为null时执行以下分配,那么newRowKey的值是否为null?

var newRowKey = vm.TempRowKey.DotFormatToRowKey();

如果dotFormatRowKey没有格式为x.x,其中x是数字,还有一种方法可以让以下内容抛出异常吗?

public static string DotFormatToRowKey(this string dotFormatRowKey) {
    var splits = dotFormatRowKey.Split('.')
                 .Select(x => String.Format("{0:d2}", Int32.Parse(x)))
                 .ToList();
    return String.Join(String.Empty, splits.ToArray());
}

6 个答案:

答案 0 :(得分:3)

  

当vm.TempRowKey为空时

然后TempRowKey.DotFormatToRowKey();将抛出一个空引用异常。

  如果dotFormatRowKey的格式不是x.x,其中x是数字,那么

抛出异常?

public static string DotFormatToRowKey(this string dotFormatRowKey) 
{
    if (dotFormatRowKey == null)
        throw new ArgumentNullException("dotFormatRowKey");    

    // maybe @"^\d\d?\.\d\d?$" is a beter regex. 
    // accept only 1|2 digits and nothing before|after
    if (! Regex.IsMatch(dotFormatRowKey, @"\d+\.\d+"))  
       throw new ArgumentException("Expected ##.##, was " + dotFormatRowKey);

    var splits = dotFormatRowKey.Split('.')
                 .Select(x => String.Format("{0:d2}", Int32.Parse(x)))
                 .ToList();  // ToList() is never needed

    // ToArray() not needed in Fx >= 4.0
    return String.Join(String.Empty, splits.ToArray()); 
}

小细节:您在ToList()上同时使用ToArray()splits。这是双重工作,在.NET 4中你也不需要。

答案 1 :(得分:3)

不,结果不会为空。您可以使用空引用调用扩展方法,但不会编写扩展方法来处理空值,因此当您尝试在空引用上使用Split方法时,您将获得一个eception。

要检查格式“x.x”,您可以检查Split的结果长度,然后使用TryParse检查值是否可以解析:

public static string DotFormatToRowKey(this string dotFormatRowKey) {
  var splits = dotFormatRowKey.Split('.');
  if (splits.Length != 2) {
    throw new FormatException("The string should contain one period.");
  }
  var s = splits.Select(x => {
    int y;
    if (!Int32.TryParse(x, out y)){
      throw new FormatException("A part of the string was not numerical");
    }
    if (y < 0 || y > 99) {
      throw new FormatExcetpion("A number was outside the 0..99 range.");
    }
    return y.ToString("d2");
  }).ToArray();
  return String.Concat(s);
}

答案 2 :(得分:0)

关于你的第一个问题..试试看看会发生什么。

第二个问题,你可以使用TryParse,如果那只是失败了......抛出异常。

答案 3 :(得分:0)

您必须检查它是否为空,否则您将获得例外。

if (null == dotFormatRowKey)
    return null;

您可以使用Regex验证模式。

Regex.IsMatch(input, "^\d+\.\d+$");

答案 4 :(得分:0)

  

如果我在vm.TempRowKey为null时执行以下任务,那么将会   newRowKey的值为null?

这会导致NullReferenceException,因为dotFormatRowKey将为null,然后您将在null值上调用Split()(这不是扩展方法)。

  

还有一种方法可以让以下内容抛出异常   如果dotFormatRowKey没有格式x.x,其中x是a   号码?

目前,使用int.Parse()强制您只有整数值和&#34;。&#34;&#39; s。它并不强制所有整数值都相同,也不强制只有1&#34;。&#34; (例如,这不会引起1.2.3)。如果您想添加其他错误检查,这很容易做到:

// test that all int values were the same (not sure if you want this but you said x.x)
if (splits.Distinct().Count() > 1) { throw new ExceptionOfSomeSort("error"); }

// test that you have exactly two values
if (splits.Count != 2) { throw new ExceptionOfSomeSort("error"); }

另一种选择是使用正则表达式预先验证整个字符串,例如:

@"\d+\.\d+"

答案 5 :(得分:0)

public static string DotFormatToRowKey(this string dotFormatRowKey)
        {
            Regex validationRegex = new Regex(@"\d.\d");
            if (!validationRegex.Match(dotFormatRowKey).Length.Equals(dotFormatRowKey.Length)) throw new FormatException("Input string does not support format x.x where x is number");

            var splits = dotFormatRowKey.Split('.')
                .Select(x => String.Format("{0:d2}", Int32.Parse(x)))
                .ToList();
            return String.Join(String.Empty, splits.ToArray());
        }