我们正在验证方法参数在函数进入时不是空的,但这对Platform::String (或Platform.String,C#和C++没有区别)不起作用,因为它们用空实例重载了空字符串的语义。
考虑这样的情况,异常总是会被抛出:
auto emptyString = ref new Platform::String();
// Now, emptyString.IsEmpty() will be true
if (emptyString == nullptr)
{
throw ref new Platform::InvalidArgumentException();
}该变量具有非null值,但==比较运算符重载,因此将其与nullptr进行比较将返回true,因为String实例为空。
据我所知,这使得我们不可能在String的函数入口进行适当的null检查。真的是这样吗?
发布于 2012-08-31 20:38:47
Windows运行时中没有“空字符串”。"Null“和"empty”对于字符串的含义是相同的。
尽管Platform::String使用^语法并且看起来像引用类型,但它不是:它是Windows Runtime基础类型HSTRING的投影。"null“HSTRING与空HSTRING没有区别。
即使Platform::String^显示为"null“(例如在调试器中),也可以安全地将其视为空字符串。您可以将其用于连接、调用s->Length()等。
在C#中,string可以是null (因此您可以测试它是否为null),但是您永远不会从Windows Runtime调用中获得null string,并且您不能将null字符串作为参数传递给Windows Runtime函数(这样做将在ABI边界产生异常)。
发布于 2012-08-31 19:39:01
看起来你是对的。任何设置为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所以,我看不出这个字符串是否曾经是nullptr的。
https://stackoverflow.com/questions/12214515
复制相似问题