gpt4 book ai didi

c# - 检查 int、string、double 等任何类型的 null 或 empty 的通用方法

转载 作者:可可西里 更新时间:2023-11-01 08:02:56 26 4
gpt4 key购买 nike

我正在尝试让它工作,但不知何故它超出了我的控制范围......我希望能够检查 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

关于c# - 检查 int、string、double 等任何类型的 null 或 empty 的通用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16560955/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com