如果变量内部的值为空,是否可以测试变量是否定义为字符串?
如果我写:
string b = null;
bool c = b is string;
然后c将为 false,因为is查看内容,该内容为 null 而不是字符串。
如果我写:
string b = null;
bool c = (b.GetType() == typeof(string));
然后它崩溃了,因为 s 是 null 并且你不能在 null 值上调用 GetType() 。
那么,我如何检查 b 以找出它是什么类型?也许是某种反思?或者有没有更简单的方法?
编辑1:澄清问题!
我的问题有点不清楚,那是我的错。在示例中,我似乎正在尝试测试变量的内容。但我想在不查看内容的情况下测试变量本身。在给出的代码示例中,我可以看到 b 是一个字符串,但是如果我不知道 b 是否是一个字符串并且只想测试变量 s 以查看它是否是一个字符串怎么办。
那么,我怎么知道变量被定义为什么类型呢?就像在这个例子中一样,但是 x 是一个未知变量,它可能被定义为一个字符串并且它也可能是 null (因为它可能是 null 这个例子不起作用)。
bool c = (x.GetType() == typeof(string));
编辑2:工作解决方案!
感谢所有给出的答案,我能够解决它。这就是工作解决方案的方式。我首先创建了一个帮助函数来测试一个变量的定义类型,即使该值为 null 并且它不指向任何东西也可以工作。
public static Type GetParameterType<T>(T destination)
{
return typeof(T);
}
然后我可以调用这个函数并测试我的“可疑字符串”并找出它是否真的是一个字符串。
// 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
这正是我想知道的!!!谢谢大家绞尽脑汁...