C# Object Type Comparison

前端 未结 4 1613
小蘑菇
小蘑菇 2021-01-30 02:04

How can I compare the types of two objects declared as type.

I want to know if two objects are of the same type or from the same base class.

Any help is apprecia

4条回答
  •  花落未央
    2021-01-30 02:42

    You can also use the "IS" keyword, if you expect the two object instances to be of a certain type. This will also work for comparing sub-classes to parent classes and also classes that implement interfaces and so forth. This will not work for types of type Type though.

    if (objA Is string && objB Is string)
    // they are the same.
    
    public class a {}
    
    public class b : a {}
    
    b objb = new b();
    
    if (objb Is a)
    // they are of the same via inheritance
    

提交回复
热议问题