Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/283.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 空值和空值_C#_.net_Robustness - Fatal编程技术网

C# 空值和空值

C# 空值和空值,c#,.net,robustness,C#,.net,Robustness,编写健壮代码以便检查变量是否为空和为空的最佳方法是什么 e、 g 对于字符串,有 if (String.IsNullOrEmpty(a)) 从2.0版开始,您可以使用 对于字符串: string a; if(!String.IsNullOrEmpty(a)) { //do something with a } 对于特定类型,可以创建扩展方法 请注意,我使用的是HasValue而不是IsNullorEmpty,因为99%的时间您都必须使用-运算符,如果您使用的是IsNullOrEmpty,我发

编写健壮代码以便检查变量是否为空和为空的最佳方法是什么

e、 g

对于字符串,有

if (String.IsNullOrEmpty(a))

从2.0版开始,您可以使用

对于字符串:

string a;
if(!String.IsNullOrEmpty(a))
{
//do something with a
}
对于特定类型,可以创建扩展方法 请注意,我使用的是HasValue而不是IsNullorEmpty,因为99%的时间您都必须使用-运算符,如果您使用的是IsNullOrEmpty,我发现它非常不可读

public static bool HasValue(this MyType value)
{
//do some testing to see if your specific type is considered filled
}

您可以定义一个扩展方法,允许您在许多事情上执行此操作:

static public bool IsNullOrEmpty<T>(this IEnumerable <T>input)
{
    return input == null || input.Count() == 0;
}
静态公共bool为空(此IEnumerable输入)
{
返回input==null | | input.Count()==0;
}

正如已经指出的那样,它已经作为字符串的静态方法存在于
系统.String
类中。

如果您使用的是.NET 4.0,您可能想看看。

我发现Apache Commons.Lang StringUtils(Java)的命名要容易得多:isEmpty()检查空字符串或空字符串,isBlank()检查空字符串或空字符串,或者只使用空格。isNullOrEmpty可能更具描述性,但在大多数情况下,空和空是一样的。

你从哪里听说过C#Net?没有这样的事情。最好使用String.IsNullOrEmpty()
String
beats
String
,因为你不必按shift键,这样你的键盘使用时间更长,也不会太累,而且你不需要
使用系统用于小写版本。(当清楚地访问一个静态类方法时,为了获得正确的大小写,使用+1和+1)引用John Skeet:但是,您绝对应该使用Any()。这样,它只需要测试第一个元素的存在。对于ICollection的正常实现来说,这将是非常便宜的,但对于涉及复杂查询的情况,这可能比Count()快得多。
public static bool HasValue(this MyType value)
{
//do some testing to see if your specific type is considered filled
}
static public bool IsNullOrEmpty<T>(this IEnumerable <T>input)
{
    return input == null || input.Count() == 0;
}
if(string.IsNullOrEmpty(string name))
{
   ///  write ur code
}