Exception when trying to read null string in C# WinRT component from WinJS

核能气质少年 提交于 2019-12-29 06:45:14

问题


I have the following scenario: Data lib in C# compiled as a Windows Runtime component.

One of its classes is looks like this:

public sealed class MyData
{
  string TheGoods { get; private set;}
}

The UI is in WinJS, and I have the following:

var b = dataInstance.theGoods;

The problem is that I get an exception and property has the following in it:

System.ArgumentNullException at System.StubHelpers.HStringMarshaler.ConvertToNative(String managed)

Looking at the implementation of HStringMarshaler.ConvertToNative, it seems to throw if the string is null.

Does that mean that it's impossible to expose a null string to WinJS? Is that a WinJS limitation or does that apply to all WinRT?

While string.Empty does work, that's not semantically the same as null and in some cases, empty is valid and different than null.

If I change the type of the property to be 'object', then it does work, but it seems nasty to expose an object when it really ought to be a string. Any ideas? The docs are pretty light on this


回答1:


The Windows Runtime string type is a value type and has no null value. The .NET projection prohibits passing a null .NET string across the Windows Runtime ABI boundary for this reason.

The string type used by the Windows Runtime is the HSTRING type. While this type does not have a null value, it does have a null representation (that is, in C++, HSTRING s = nullptr; is valid). An HSTRING with a null representation is an empty string.

The .NET projection converts this null representation into an empty string (String.Empty) for strings coming in from the ABI boundary, and prohibits actual null .NET strings from being passed back across the ABI boundary.



来源:https://stackoverflow.com/questions/12980915/exception-when-trying-to-read-null-string-in-c-sharp-winrt-component-from-winjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!