How to compare types

后端 未结 5 1631
半阙折子戏
半阙折子戏 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:36

    If your instance is a Type:

    Type typeFiled;
    if (typeField == typeof(string))
    { 
        ... 
    }
    

    but if your instance is an object and not a Type use the as operator:

    object value;
    string text = value as string;
    if (text != null)
    {
        // value is a string and you can do your work here
    }
    

    this has the advantage to convert value only once into the specified type.

提交回复
热议问题