Skip to main content
 首页 » 编程设计

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

2024年02月20日46zhoujg

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

C#:

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

C++/CLI,接口(interface):

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当我将可为空定义为引用时。我可以离开 Actor 阵容并继续前进吗?还是我做错了什么?

请您参考如下方法:

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

这对于可空值来说比普通值类型更没有意义,因为可空值被装箱为其基础类型。

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