Test if object implements interface

前端 未结 12 1548
情歌与酒
情歌与酒 2020-11-28 01:03

What is the simplest way of testing if an object implements a given interface in C#? (Answer to this question in Java)

相关标签:
12条回答
  • 2020-11-28 01:24

    This Post is a good answer.

    public interface IMyInterface {}
    
    public class MyType : IMyInterface {}
    

    This is a simple sample:

    typeof(IMyInterface).IsAssignableFrom(typeof(MyType))
    

    or

    typeof(MyType).GetInterfaces().Contains(typeof(IMyInterface))
    
    0 讨论(0)
  • 2020-11-28 01:26
    if (object is IBlah)
    

    or

    IBlah myTest = originalObject as IBlah
    
    if (myTest != null)
    
    0 讨论(0)
  • 2020-11-28 01:27

    Using the is or as operators is the correct way if you know the interface type at compile time and have an instance of the type you are testing. Something that no one else seems to have mentioned is Type.IsAssignableFrom:

    if( typeof(IMyInterface).IsAssignableFrom(someOtherType) )
    {
    }
    

    I think this is much neater than looking through the array returned by GetInterfaces and has the advantage of working for classes as well.

    0 讨论(0)
  • 2020-11-28 01:28

    This should work :

    MyInstace.GetType().GetInterfaces();
    

    But nice too :

    if (obj is IMyInterface)
    

    Or even (not very elegant) :

    if (obj.GetType() == typeof(IMyInterface))
    
    0 讨论(0)
  • 2020-11-28 01:32

    What worked for me is:

    Assert.IsNotNull(typeof (YourClass).GetInterfaces().SingleOrDefault(i => i == typeof (ISomeInterface)));

    0 讨论(0)
  • For the instance:

    if (obj is IMyInterface) {}
    

    For the class:

    Check if typeof(MyClass).GetInterfaces() contains the interface.

    0 讨论(0)
提交回复
热议问题