无法将类型'System.ValueType'隐式转换为'int?' - c#

我有一个C ++ / CLI包装器类,可在C#和本机C ++之间互操作。我收到与System.Nullable相关的奇怪错误。我了解,对于基本类型,System.Nullable<T>等效于T?。所以我这样做:

C#:

public int? RoboticsArmRotation {
   get { return mRobotics.ArmRotation; }
}

C ++ / CLI,接口:

virtual property System::Nullable<int>^ ArmRotation{ System::Nullable<int>^ get() = 0; }

C ++ / CLI,具体类别:

virtual property System::Nullable<int>^ ArmRotation {
    System::Nullable<int>^ get() {
        boost::optional<int> value = m_pNativeInstance->getArmRotation();
        return value.is_initialized()? gcnew System::Nullable<int>(value.get()) : gcnew System::Nullable<int>();
    }
}

但是我得到标题的编译错误。强制转换为int?可以解决此问题,但令我感到困扰的是,当我将我的空值定义为引用时,它说的是System.ValueType。我可以离开剧组继续前进,还是我做错了什么?

参考方案

您正在使用Nullable<int>^作为参考。由于运行时不直接支持具有值类型的引用,因此IL级别的实际类型是ValueType,该类型用C ++ / CLI支持的方式用Nullable<int>^标记,但C#不支持。对于C#,只需将其键入为System.ValueType

这对可空值的意义甚至比普通值类型的意义更小,因为可空值被装箱作为其基础类型。

我建议也不要将字段声明为C ++中的引用,而是使用简单的Nullable<int>

如何解析Dapper System.Data.DataException HResult = 0x80131501 InvalidCastException从'System.String'到'System.Uri'的无效转换 - c#

最近,我重构了一些代码,这些代码导致将实体的某些属性的类型从System.String更改为System.URI。有问题的属性名称包含子字符串URI或URL,并且SonarLint静态代码分析器建议将代码重构为对这些属性使用System.URI类型而不是System.String,这在我们的解决方案中很有意义。在这个项目中,我们利用StackExchange…

将字符串分配给numpy.zeros数组[重复] - python

This question already has answers here: Weird behaviour initializing a numpy array of string data                                                                    (4个答案)         …

AttributeError:'AnonymousUserMixin'对象没有属性'can' - python

烧瓶学习问题为了定制对匿名用户的要求,我在模型中设置了一个类: class MyAnonymousUser(AnonymousUserMixin): def can(self, permissions): return False def is_administrator(self): return False login_manager.anonymous…

如何在python中连接熊猫数据框 - python

我有一个python对象列表,有些像这样team_1_players1=[] is a list 在team_1_players1 = []内部,存储了多个json对象。1st Json Object像这样[[{'age_days': '72', 'age_years': '30'…

TypeError:'str'对象不支持项目分配,带有json文件的python - python

以下是我的代码import json with open('johns.json', 'r') as q: l = q.read() data = json.loads(l) data['john'] = '{}' data['john']['use…