C++/CLI 中的 System::Object 到 int 或 double
我正在从数据库中获取一些信息,我想在计算中使用它。但由于我写的内容,我无法将其转换为数字。我收到 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
。我该如何改造它?
I'm taking some information from data base and i want to use it in calculations. But due to what i'written, i'm not able to convert it to number. I recieve System::Object^
. here is the part of code:
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...");
I want to use numberOfProducts
as a digit. I mean type double
or integer
. How can i transform it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
只需使用
safe_cast
即可投射Object^
为适当的类型。本页对此进行了详细介绍:如何:在 C++/CLI 中使用 safe_cast< /a>由于只能有一种基础类型(而且我不知道你的情况是什么),因此只有其中一种可以工作——另一种会抛出异常。重点是,第一步是确定实际的基础类型(大概是 double、float 或 int)。
Simply use
safe_cast
to cast theObject^
to the appropriate type. This is covered in detail on this page: How to: Use safe_cast in C++/CLISince there can only be one underlying type (and I don't know what it is in your case), only one of these will work -- the other will throw an exception. Point being, your first step is to determine the actual underlying type (presumably
double
,float
, orint
).