How to check an object's type in C++/CLI?

偶尔善良 提交于 2019-12-10 01:25:51

问题


Is there a simple way to check the type of an object? I need something along the following lines:

MyObject^ mo = gcnew MyObject();
Object^ o = mo;

if( o->GetType() == MyObject )
{
    // Do somethine with the object
}
else
{
    // Try something else
}

At the moment I'm using nested try-catch blocks looking for System::InvalidCastExceptions which feels ugly but works. I was going to try and profile something like the code above to see if it's any faster/slower/readable but can't work out the syntax to even try.

In case anyone's wondering, this comes from having a single queue entering a thread which supplied data to work on. Occasionally I want to change settings and passing them in via the data queue is a simple way of doing so.


回答1:


You can use MyObject::typeid in C++/CLI the same way as typeof(MyObject) is used in C#. Code below shamelessly copied from your question and modified ...

MyObject^ mo = gcnew MyObject();
Object^ o = mo;

if( o->GetType() == MyObject::typeid )
{
    // Do somethine with the object
}
else
{
    // Try something else
}



回答2:


You should check out How to: Implement is and as C# Keywords in C++:

This topic shows how to implement the functionality of the is and as C# keywords in Visual C++.




回答3:


edit: I will leave this here. But this answer is for C++. Probably not even slightly related to doing this for the CLI.

You need to compile with RTTI(Run Time Type Information) on. Then look at the wikipedia article http://en.wikipedia.org/wiki/Run-time_type_information and search google for RTTI. Should work for you.

On the other hand you might want to have a virtual base class for all your data classes with a member variable that describes what type it is.



来源:https://stackoverflow.com/questions/2410721/how-to-check-an-objects-type-in-c-cli

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!