如果它是一个字符串,如何测试一个空值变量?

Ohl*_*lin 6 c# string null

如果变量被定义为字符串,如果其中的值为null,是否可以测试它?

如果我写:

string b = null;
bool c = b is string;
Run Code Online (Sandbox Code Playgroud)

然后c将为false,因为它会查看内容,该内容为null而不是字符串.

如果我写:

string b = null;
bool c = (b.GetType() == typeof(string)); 
Run Code Online (Sandbox Code Playgroud)

然后它崩溃,因为s为null,你不能在空值上调用GetType().

那么,我如何检查b以找出它是什么类型?某种反思可能吗?或者有更简单的方法吗?

编辑1:澄清问题!

我的问题有点不清楚,这是我的错.在示例中,它看起来像我正在尝试测试变量的内容.但我想在不查看内容的情况下测试变量本身.在给出的代码示例中,我可以看到b是一个字符串,但是如果我不知道b是否是字符串并且只想测试变量s以查看它是否是字符串.

那么,我怎么知道变量被定义为什么类型?如本例所示,但x是一个未知变量,可能被定义为一个字符串,它也可能是null(因为它可能为null,这个例子不起作用).

bool c = (x.GetType() == typeof(string)); 
Run Code Online (Sandbox Code Playgroud)

编辑2:工作解决方案!

感谢所有答案,我能够解决它.这就是工作解决方案的成果.我首先创建了一个帮助函数来测试一个变量的定义类型,即使该值为null并且它没有指向任何东西也是如此.

public static Type GetParameterType<T>(T destination)
{
    return typeof(T);
}
Run Code Online (Sandbox Code Playgroud)

然后我可以调用此函数并测试我的"疑似字符串",并查明它是否真的是一个字符串.

// We define s as string just for this examples sake but in my "definition" we wouldn't be sure about whether s is a string or not.
string s = null; 

// Now we want to test to see if s is a string
Type t = GetParameterType(s);
b = t == typeof(string);  // Returns TRUE because s has the type of a string
b = t is string;  // Returns FALSE because the content isn't a string
Run Code Online (Sandbox Code Playgroud)

这正是我想要找到的!谢谢大家挤压你的大脑......

Mat*_*son 11

您不能检查的类型null,因为null 没有类型.它根本没有引用任何东西,因此C#没有任何东西可以查找实际类型.

(其他人似乎都在回答这个问题"如何判断字符串引用是空还是空 - 但我认为问题是"如何判断空引用的基础类型是否string......)

可能有一种方法可以摆弄它 - 你可以使用这里提到的通用方法:

.NET:如何获得null对象的Type?

(该链接是由其他人发布的 - 而非我 - 作为对您原始帖子的评论!)

  • +1到目前为止这个微妙问题唯一明智的答案 (2认同)