C# 使用反射时检查null

C# 使用反射时检查null,c#,C#,我正在使用反射将对象转换为csv。有时,我会得到引发异常的null值,因此我决定检查null并用空字符串替换null。然而,我得到了一个错误,因为我无法将对象转换为字符串。问题出在这行代码中 if(properties[i].GetValue(this)是字符串&& string.IsNullOrEmpty(属性[i].GetValue(此))) 公共抽象类CsvableBase { 公共虚拟字符串ToCsv() { 字符串输出=”; var properties=GetType().GetPr

我正在使用反射将对象转换为csv。有时,我会得到引发异常的null值,因此我决定检查null并用空字符串替换null。然而,我得到了一个错误,因为我无法将对象转换为字符串。问题出在这行代码中

if(properties[i].GetValue(this)是字符串&& string.IsNullOrEmpty(属性[i].GetValue(此)))

公共抽象类CsvableBase
{
公共虚拟字符串ToCsv()
{
字符串输出=”;
var properties=GetType().GetProperties();
对于(var i=0;i
虽然运行时
GetValue()
返回的值是一个字符串,但
GetValue()
返回类型是
对象
,因此不强制转换就无法将其传递给
string.IsNullOrEmpty()

你可以这样做:

if(properties[i].GetValue(this) is String s 
   && string.IsNullOrEmpty(s))
在C#7之前,它会更加冗长:

object o = properties[i].GetValue(this);
string s = o as string;
if (string.IsNullOrEmpty(s))
{ /*...*/ }

你想得太多了。只需在for循环的顶部计算一次值,然后检查一次null

您不需要尝试区分字符串null和其他类型的null。在运行时,它们都将只是空对象

您不需要
+=”
,因为这不起任何作用

for (var i = 0; i < properties.Length; i++)
{
    object value = properties[i].GetValue(this);
    if (value == null)
    {
        //do nothing
    }
    else if (value is DateTime)
    {
         output += ((DateTime)value).ToString("yyyy-MM-dd HH:mm:ss");
    }
    else
    {
         output += value.ToString();
    }

    if (i != properties.Length - 1)
    {
        output += ",";
    }
}
显然是错误的,因为如果该值为null,则您有:

else if (null is String && string.IsNullOrEmpty(properties[i].GetValue(this)))
null为字符串
为false。

右边的代码只有在值不为null时才会运行,这是毫无意义的。

这是C版本的吗???(我不记得是6.0还是7.0)并不是每个人都在使用它。re:你的旁注,
string.IsNullOrEmpty(“”)
返回true,所以它并非毫无意义。但是仍然很难理解OP认为IsNullOrEmpty()的“IsNull”部分是什么意思。或者为什么他没有通过编写一个静态方法来简化代码
IsNullOrIsNullOrEmptyOrIsNull()
@EdPlunkett同样,空字符串大小写也不是特例<代码>输出+=“”vs
output+=properties[i].GetValue(this.ToString()的行为都是一样的。很好的一点,我没有看到他在用字符串做什么。
else if (properties[i].GetValue(this) is String && string.IsNullOrEmpty(properties[i].GetValue(this)))
else if (null is String && string.IsNullOrEmpty(properties[i].GetValue(this)))