How to compare types

后端 未结 5 1630
半阙折子戏
半阙折子戏 2020-12-13 22:50

Quick question: how to compare a Type type (pun not intended) with another type in C#? I mean, I\'ve a Type typeField and I want to know if it is System.S

5条回答
  •  心在旅途
    2020-12-13 23:15

    Try the following

    typeField == typeof(string)
    typeField == typeof(DateTime)
    

    The typeof operator in C# will give you a Type object for the named type. Type instances are comparable with the == operator so this is a good method for comparing them.

    Note: If I remember correctly, there are some cases where this breaks down when the types involved are COM interfaces which are embedded into assemblies (via NoPIA). Doesn't sound like this is the case here.

提交回复
热议问题