我从数据库中获取一些信息,我想在计算中使用它。但由于我写的东西,我无法将其转换为数字。我收到了System::Object^
。这是代码的一部分:
OleDbConnection ^ cnNwind = gcnew OleDbConnection();
cnNwind-> ConnectionString =
L"Provider = Microsoft.Jet.OLEDB.4.0;"
L"Data Source = C:\\temp\\A.mdb";
try
{
// Open the database
cnNwind->Open();
Console::WriteLine(L"Connected to database successfully!");
// Count the customers
OleDbCommand ^ cmProducts = gcnew OleDbCommand();
cmProducts->CommandText = L"SELECT ID FROM Table1";
cmProducts->CommandType = CommandType::Text;
cmProducts->Connection = cnNwind;
// Print the result
Object ^ numberOfProducts = cmProducts->ExecuteScalar();
Console::Write(L"Number of products: ");
Console::WriteLine(numberOfProducts);
}
catch (OleDbException ^ pe)
{
Console::Write(L"Error occurred: ");
Console::WriteLine(pe->Message);
}
// Close the connection
if (cnNwind->State != ConnectionState::Closed)
{
cnNwind->Close();
}
Console::WriteLine(L"The database connection is closed...");
我想将numberOfProducts
用作数字。我的意思是键入double
或integer
。我怎样才能改变它?
答案 0 :(得分:4)
只需使用safe_cast
将Object^
转换为适当的类型即可。本页详细介绍了这一点:How to: Use safe_cast in C++/CLI
Object^ numberOfProductsObj = cmProducts->ExecuteScalar();
// IIF the underlying type is System::Int32
int numberOfProducts = safe_cast<int>(numberOfProductsObj);
// or, IIF the underlying type is System::Double
double numberOfProducts = safe_cast<double>(numberOfProductsObj);
因为只能有一个底层类型(我不知道你的情况是什么),只有其中一个可以工作 - 另一个会抛出异常。重点是,您的第一步是确定实际的基础类型(可能是double
,float
或int
)。