Windows runtime 如何区分空的Platform.String和空的Platform.String^

Windows runtime 如何区分空的Platform.String和空的Platform.String^,windows-runtime,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 r

我们正在验证方法参数在函数输入时是否不为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();
}
该变量具有非空值,但
=
比较运算符重载,因此将其与
nullptr
进行比较将返回true,因为
字符串
实例为空


据我所知,这使得我们不可能在函数项中对
String
s进行适当的空检查。真的是这样吗?看来你是对的。任何设置为
nullptr
的字符串都被视为空字符串。如果您甚至将
nullptr
传递给函数,您将永远不会得到
NullReferenceException

bool NullPtrTest(Platform::String^ value)
{
  return value == nullptr;
}

bool EmptyTest(Platform::String^ value)
{
  return value->IsEmpty();
}

bool ReferenceEqualsWithNullPtrTest(Platform::String^ value)
{
  return Platform::String::ReferenceEquals(nullptr, value);
}

bool EqualsWithValueTest(Platform::String^ value)
{
  return value->Equals("test");
}

//...

NullPtrTest(nullptr); // true
NullPtrTest(ref new Platform::String()); // true
NullPtrTest("test"); // false


EmptyTest(nullptr); // true - no exception
EmptyTest(ref new Platform::String()); // true
EmptyTest("test"); // false


ReferenceEqualsWithNullPtrTest(nullptr); // true
ReferenceEqualsWithNullPtrTest(ref new Platform::String()); // true
ReferenceEqualsWithNullPtrTest("test"); // false


EqualsWithValueTest(nullptr); // false - no exception
EqualsWithValueTest(ref new Platform::String()); // false
EqualsWithValueTest("test"); // true
因此,我看不到任何方法来确定字符串是否为
null ptr

在Windows运行时中没有“null字符串”。“Null”和“empty”对于字符串的含义相同

尽管
Platform::String
使用了
^
语法,看起来像是引用类型,但事实并非如此:它是Windows运行时基本类型的投影。“null”hs字符串与空hs字符串无法区分

即使
Platform::String^
显示为“null”(例如在调试器中),也可以安全地将其视为空字符串。您可以使用它进行连接,调用
s->Length()
,等等



在C#中,
字符串
可以为null(因此您可以测试它是否为null),但您永远不会从Windows运行时调用中获得null
字符串
,并且无法将null字符串作为参数传递给Windows运行时函数(这样做将在ABI边界处产生异常)。

。在不可变类型上使用默认构造函数不是一个好主意。Platform::String是故意损坏的,您应该使用std::wstring。还考虑SrimeRebug来避免复制字符串。遗留代码(是的,尽管它是WRRT),但我们不控制该类型。这是我缺少的一部分:…您不能将空字符串作为参数传递给Windows运行时函数-这意味着我们不需要检查nullptr,因为它永远不会是这样。请参阅我对James答案的评论