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

时间:2012-08-31 11:34:37

标签: 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();
}

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

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

2 个答案:

答案 0 :(得分:9)

Windows运行时中没有“空字符串”。 “Null”和“empty”对于字符串意味着相同的事情。

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

即使Platform::String^看起来是“空”(例如在调试器中),也可以将其视为空字符串。您可以使用它进行连接,调用s->Length()


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

答案 1 :(得分:1)

似乎你是对的。设置为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