检查任何类型如int, string, double的null或empty的通用方法
本文关键字:null 方法 empty double 类型 任何 int string 检查 | 更新日期: 2023-09-27 18:13:33
我正试图让这个工作,但不知何故它走出了我的手…我想检查我赋给的类型是否为null或empty。
,
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
}
有人能帮我一下吗?我想了解这个简单方法的泛型是如何工作的
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));
}
如何使用:
class Stub { }
bool f1 = CheckNullOrEmpty(""); //true
bool f2 = CheckNullOrEmpty<string>(null); //true
bool f3 = CheckNullOrEmpty(0); //true
bool f4 = CheckNullOrEmpty<Stub>(null); //true
您可以检查default(T);
public bool CheckNullOrEmpty<T>(T value)
{
return value == default(T);
}
更多信息:http://msdn.microsoft.com/en-us/library/xwth0h0d.aspx
可以使用default() -
例如:
if(value != default(T))
从MSDN: 给定一个参数化类型t的变量t,语句t = null仅当T是引用类型时有效,并且T = 0仅适用于数值类型,但不用于结构体。解决方法是使用默认关键字,它将为引用类型返回null和零用于数值类型。对于结构体,它将返回的每个成员结构体初始化为零或空,取决于它们是否为零值或引用类型
http://msdn.microsoft.com/en-us/library/xwth0h0d (v = vs.80) . aspx
由于您的CheckNullOrEmpty
实现类型不同,因此您不能将该检查作为泛型函数。
如果使用Nullable
值类型,则可以使用GetValueOrDefault()
:
int? i = 0;
var result = i.GetValueOrDefault(10);
对于string
,只需要一个扩展方法:
public static string GetValueOrDefault(this string item, string defaultValue = "")
{
return !string.IsNullOrWhiteSpace(item) ? item : defaultValue;
}
那么你可以这样做:
string i = null;
string mystring = "";
var result = i.GetValueOrDefault(mystring);
我添加了几个重构:1. DBNull不被视为isnullorempty,因此添加了(值作为字符串)2. 传递在运行时动态创建的数据表row[column](如:row["PropertyName"])将不会将其视为类型为(T)的字符串,因为列类型基是object。因此增加了typeof(object)的额外检查,如果不是null,则测试ToString()是否为空值。我还没有完全测试过,所以可能不适用于所有类型的数据列。之前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)); }
如果你知道T是class,那么所有的class都可以为null,你可以这样检查:
public bool CheckIsDefault<T>(T value)
where T: class
{
return value == default(T);
}