Test if object implements interface

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

提交回复
热议问题