Test if object implements interface

前端 未结 12 1592
情歌与酒
情歌与酒 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: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);
    

提交回复
热议问题