简体   繁体   English

C#中的字符串和C ++ / CLI中的String ^ ...如何传递“null”?

[英]string in C# and String^ in C++/CLI… How to pass “null”?

I got some C++ library. 我有一些C ++库。 And also I got C++/CLI wrapper for it, to make it possible call methods from this library in C# code. 我还得到了C ++ / CLI包装器,以便在C#代码中调用来自该库的方法。

Lets say I would like to use some call in C# like this: 假设我想在C#中使用一些调用,如下所示:

string date = MyWrapper.GetValue("SystemSettings", "BuildDate", null);

which will call next function on C++/CLI: 它将在C ++ / CLI上调用next函数:

static String^ GetValue(String^ section, String^ key, String^ defaultValue)

My problem: I got next ArgumentNullException: 我的问题:我有下一个ArgumentNullException:

Value cannot be null.\\r\\nParameter name: managedString. 值不能为null。\\ r \\ nParameter name:managedString。

So... Question: how should I pass null correctly? 所以...问题:我应该如何正确传递null Thanks. 谢谢。

Your code that passes null is fine. 传递null的代码很好。 The problem is that your wrapper code needs to detect null and deal with it. 问题是你的包装器代码需要检测null并处理它。 That code is presumably written under the assumption that the third parameter is never null. 该代码可能是在假设第三个参数永远不为空的情况下编写的。 If you wish to allow null, you must explicitly handle that condition: 如果您希望允许null,则必须显式处理该条件:

static String^ GetValue(String^ section, String^ key, String^ defaultValue)
{
    if (defaultValue == nullptr)
        // special case handling
    ....
}

There is a similar limitation for Windows Runtime. Windows运行时也有类似的限制。 See this verbose answer to a similar question . 这个冗长回答一个类似的问题 Looks like you might have trapped on something very close to it. 看起来你可能已经陷入了非常接近它的东西。

Maybe you need to pass an empty string instead of null. 也许你需要传递一个空字符串而不是null。 For example 例如

string date = MyWrapper.GetValue("SystemSettings", "BuildDate", "");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM