如何区分空Platform.String和null Platform.String ^

Joh*_*ell 4 windows-runtime

我们验证方法参数在函数入口时不为null,但这不适用于Platform::String(或者Platform.String,C#或C++之间没有区别),因为它们使用null实例重载空字符串的语义.

考虑一下,总会抛出异常:

auto emptyString = ref new Platform::String();

// Now, emptyString.IsEmpty() will be true

if (emptyString == nullptr)
{
    throw ref new Platform::InvalidArgumentException();
}
Run Code Online (Sandbox Code Playgroud)

该变量具有非null值,但==比较运算符已重载,因此将其nullptr与String实例为空时返回true 进行比较.

据我所知,这使得我们无法在Strings的函数入口处进行适当的空值检查.真的是这样吗?

Jam*_*lis 10

Windows运行时中没有"空字符串"."Null"和"empty"对于字符串来说意味着相同的东西.

尽管Platform::String使用^语法并且看起来像引用类型,但它不是:它是Windows运行时基本类型的投影HSTRING."空"HSTRING与空HSTRING无法区分.

即使a Platform::String^似乎是"null"(例如在调试器中),也可以将其视为空字符串.您可以使用它进行连接,调用s->Length()等.


在C#中,a string可以为null(因此您可以将其测试为null),但是您永远不会string从Windows运行时调用中获取null 并且您不能将空字符串作为参数传递给Windows运行时函数(这样做会产生ABI边界的一个例外).