Test if object implements interface

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

提交回复
热议问题