开发者

C# in VS2005: determining what type an Object really is

In C# using VS2005, if I have a variable of t开发者_Python百科ype Object, to which I assign a MyObjectType object by casting as follows:

MyObjectType myObj = GetMyObject();
Object obj = (Object)myObj;

Is there way to determine that obj is actually a MyObjectType and not just an Object?


Absolutely:

if (obj is MyObjectType)
{
    ...
}

Or, if you want to then use some members of it:

MyObjectType mot = obj as MyObjectType;
if (mot != null)
{
    ...
}

Note that these will work even if obj refers to an object derived from MyObjectType. If you only want an exact match, you should use:

if (obj != null && obj.GetType() == typeof(MyObjectType))

... but that's a pretty rare use case in my experience.


If you want to check if obj is a MuObjectType you can write

if( obj is MyObjectType)

This returns true if obj is infact a MyObjectType, else false.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜