问题描述
这是我的代码:
Here is my code:
void Simulate::DisplayString(String ^stString)
{
DateTime ^stTimeString = DateTime::Now;
String ^stTempString = String::Empty;
TempString = stTimeString->ToString("HH:mm");
stTempString = stTempString + " " + stString;
myListbox->Items->Add(stTempString);
}
它可以编译并链接OK,但是当它运行时,它在最后一行得到以下错误.
It compiles and links OK but when it runs, it get the following error on the last line.
An unhandled exception of type 'System.NullReferenceException' occurred
in System.Windows.Forms.dll
Additional information: Object reference not set to an instance of an object.
如何使szTempString成为对象的实例而不是引用?
How do I get szTempString to be an instance of the object instead of a reference?
推荐答案
myListBox->Items->Add( String::Format( "Item {0}", stTempString) );
or try
objString = gcnew(stTempString) where gcnew is new operator or its equivalent
谢谢
Thanks
TempString = stTimeString->ToString("HH:mm");
我不知道还有什么是不真实的.
因此,不要让每个人和自己感到困惑,发布真实代码.同时...
该代码表明您不了解事情的工作方式:
I don''t know what else is not authentic.
So, stop confusing everyone and yourself, post the real code. In the meanwhile…
The code shows that you don''t understand how things work:
//why do you call ^stTimeString string?!! It's DateTime:
DateTime ^stTimeString = DateTime::Now;
//congratulations: String::Empty is way better then "";
//however the assignment makes no sense:
String ^stTempString = String::Empty;
//I fixed this line; was "TempString":
stTempString = stTimeString->ToString("HH:mm");
//+ + is very bad: remember, string is immutable,
//so this is very ineffective:
stTempString = stTempString + " " + stString;
//use String::Format("{0} {1}", stTempString, stString);
//as stString does not exist
//I'm not sure myListbox^ was instantiated before
myListbox->Items->Add(stTempString)
您真正需要的只是这个:
All you really need is this:
myListbox->Items->Add(System::String::Format(
"{0} {1}",
System::DateTime::Now,
stString));
现在,命名:使用(好的)Microsoft命名约定.摆脱前缀"st".在变量名中使用类型名是很愚蠢的.这与在EXE文件的命名中使用名称应用程序"或程序"相同,在类的名称中使用名称"class"等.名称应具有语义.由于还不够,您的名字"stTimeString"令人困惑-它不是字符串.
请考虑到这一点.如果仍然没有解决方案,请提供我要求的信息.
Now, naming: use (good) Microsoft naming conventions. Get rid of prefix "st". Using the name of the type in the name of variable is quite silly. This is the same as use the name "application" or "program" in the naming of EXE file, "class" in the name of class, etc. Names should be semantic. As it was not enough, your name "stTimeString" is confusing — it is not a string.
Please take this into account. If you still did not got the solution, please provide the information I requested.
这篇关于使用C ++/CLI在列表框中显示字符串的句柄的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!