C# 检查任何类型(如 int、string、double)的 null 或空的通用方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16560955/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 01:21:19  来源:igfitidea点击:

generic way to check null or empty for any type like int, string, double

c#generics

提问by patel.milanb

I am trying t get this working but somehow its going out of my hand... I want to be able to check null or empty to whatever type i assigned.

我正在尝试让它工作,但不知何故它超出了我的控制......我希望能够检查我分配的任何类型的空值或空值。

EX:

前任:

int i =0;
string mystring = "";

var reult  = CheckNullOrEmpty(10) // passing int
var result 1  = CheckNullOrEmpty(mystring) // passing string 

 public bool CheckNullOrEmpty<T>(T value)
 {
    // check for null or empty for strings
    // check for null i.e. 0 for int 

 }

can someone help me with this.. I am trying to understand how generics works for this simple method.

有人可以帮我解决这个问题吗..我试图了解泛型如何用于这个简单的方法。

采纳答案by cuongle

public static bool CheckNullOrEmpty<T>(T value)
{
     if (typeof(T) == typeof(string))
        return string.IsNullOrEmpty(value as string);

     return value == null || value.Equals(default(T));
}

How to use:

如何使用:

class Stub { }

bool f1 = CheckNullOrEmpty(""); //true
bool f2 = CheckNullOrEmpty<string>(null); //true
bool f3 = CheckNullOrEmpty(0); //true
bool f4 = CheckNullOrEmpty<Stub>(null);  //true

回答by Dave Bish

You can use default() -

您可以使用 default() -

e.g.:

例如:

if(value != default(T))

from MSDN:

来自 MSDN:

Given a variable t of a parameterized type T, the statement t = null is only valid if T is a reference type and t = 0 will only work for numeric value types but not for structs. The solution is to use the default keyword, which will return null for reference types and zero for numeric value types. For structs, it will return each member of the struct initialized to zero or null depending on whether they are value or reference types.

给定参数化类型 T 的变量 t,语句 t = null 仅在 T 是引用类型时才有效,并且 t = 0 仅适用于数值类型而不适用于结构。解决方案是使用 default 关键字,它将为引用类型返回 null,为数值类型返回零。对于结构,它将返回结构的每个成员初始化为零或空值,具体取决于它们是值类型还是引用类型。

http://msdn.microsoft.com/en-us/library/xwth0h0d(v=vs.80).aspx

http://msdn.microsoft.com/en-us/library/xwth0h0d(v=vs.80).aspx

回答by mattytommo

Because your CheckNullOrEmptyimplementation differs by type, you can't have that check as a generic function.

因为您的CheckNullOrEmpty实现因类型而异,所以您不能将该检查作为通用函数。

If you use Nullablevalue types however, you can use GetValueOrDefault():

Nullable但是,如果您使用值类型,则可以使用GetValueOrDefault()

int? i = 0;

var result = i.GetValueOrDefault(10);

Then for string, just have an extension method:

然后 for string,只需要一个扩展方法:

public static string GetValueOrDefault(this string item, string defaultValue = "")
{
    return !string.IsNullOrWhiteSpace(item) ? item : defaultValue;
}

Then you can do:

然后你可以这样做:

string i = null;
string mystring = "";

var result  = i.GetValueOrDefault(mystring);

回答by nein.

You can check against default(T);

你可以对照 default(T);

 public bool CheckNullOrEmpty<T>(T value)
 {
      return value == default(T);
 }

For more informations: http://msdn.microsoft.com/en-us/library/xwth0h0d.aspx

有关更多信息:http: //msdn.microsoft.com/en-us/library/xwth0h0d.aspx

回答by rjean99

I've added a couple of re-factorings:

 1. DBNull is not seen as isnullorempty so added the (value as string)
 2. Passing a datatable row[column] that was created dynamically at runtime (like: row["PropertyName"]) will not see this as a string with typeof(T) due to the fact that the column type base is object. So added an extra check for typeof(object) and if not null test that the ToString() is empty value. I haven't tested this fully so may not work for all types of data columns.
  public static bool CheckNullOrEmpty<T>(T value)
  {
        // note: this does not see DBNull as isnullorempty.  
        if (typeof(T) == typeof(string))
        {
            if (!string.IsNullOrEmpty(value as string))
            {
                return string.IsNullOrEmpty(value.ToString().Trim());
            }
            else
            {
                return true;
            }
        }
        else if (typeof(T) == typeof(object))
        {
            // note: datatable columns are always seen as object at runtime with generic T regardless of how they are dynamically typed?
            if (value != null) {
                return string.IsNullOrEmpty(value.ToString().Trim());
            }
        }


      return value == null || value.Equals(default(T));
  }