Finding out if a type implements a generic interface

后端 未结 7 1781
深忆病人
深忆病人 2020-12-01 05:49

Let\'s say I have a type, MyType. I want to do the following:

  1. Find out if MyType implements the IList interface, for some T.
  2. If the answer to (1) is y
相关标签:
7条回答
  • 2020-12-01 06:44

    If i understand your question correctly, this is what you are trying to do. If not, please explain further.

    public class MyType : ISomeInterface
    {
    }
    
    MyType o = new MyType();
    
    if(o is ISomeInterface)
     {
     }
    

    edit: if you change your question, please add the fact that you edited..because now my answer looks like it doesn't belong.

    In that case, here is a very large LINQ

                var item = typeof(MyType).GetInterfaces()
                                .Where(x => x.IsGenericType && x.GetGenericTypeDefinition() == typeof(IList<>))
                                .Select(t => t.GetGenericArguments().First())
                                .FirstOrDefault();
    
    if( item != null )
     //it has a type
    
    0 讨论(0)
提交回复
热议问题