Test if object implements interface

前端 未结 12 1547
情歌与酒
情歌与酒 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:14

    If you want to use the typecasted object after the check:
    Since C# 7.0:

    if (obj is IMyInterface myObj)
    

    This is the same as

    IMyInterface myObj = obj as IMyInterface;
    if (myObj != null)
    

    See .NET Docs: Pattern matching with is # Type pattern

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

    I used

    Assert.IsTrue(myObject is ImyInterface);

    for a test in my unit test which tests that myObject is an object which has implemented my interface ImyInterface.

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

    In addition to testing using the "is" operator, you can decorate your methods to make sure that variables passed to it implement a particular interface, like so:

    public static void BubbleSort<T>(ref IList<T> unsorted_list) where T : IComparable
    {
         //Some bubbly sorting
    }
    

    I'm not sure which version of .Net this was implemented in so it may not work in your version.

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

    I had a situation where I was passing a variable to a method and wasn't sure if it was going to be an interface or an object.

    The goals were:

    1. If item is an interface, instantiate an object based on that interface with the interface being a parameter in the constructor call.
    2. If the item is an object, return a null since the constuctor for my calls are expecting an interface and I didn't want the code to tank.

    I achieved this with the following:

        if(!typeof(T).IsClass)
        {
           // If your constructor needs arguments...
           object[] args = new object[] { my_constructor_param };
           return (T)Activator.CreateInstance(typeof(T), args, null);
        }
        else
           return default(T);
    
    0 讨论(0)
  • 2020-11-28 01:19

    Recently I tried using Andrew Kennan's answer and it didn't work for me for some reason. I used this instead and it worked (note: writing the namespace might be required).

    if (typeof(someObject).GetInterface("MyNamespace.IMyInterface") != null)
    
    0 讨论(0)
  • 2020-11-28 01:22

    A variation on @AndrewKennan's answer I ended up using recently for types obtained at runtime:

    if (serviceType.IsInstanceOfType(service))
    {
        // 'service' does implement the 'serviceType' type
    }
    
    0 讨论(0)
提交回复
热议问题