How to compare types

后端 未结 5 1596
半阙折子戏
半阙折子戏 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.

    0 讨论(0)
  • 2020-12-13 23:20

    You can compare for exactly the same type using:

    class A {
    }
    var a = new A();
    var typeOfa = a.GetType();
    if (typeOfa == typeof(A)) {
    }
    

    typeof returns the Type object from a given class.

    But if you have a type B, that inherits from A, then this comparison is false. And you are looking for IsAssignableFrom.

    class B : A {
    }
    var b = new B();
    var typeOfb = b.GetType();
    
    if (typeOfb == typeof(A)) { // false
    }
    
    if (typeof(A).IsAssignableFrom(typeOfb)) { // true
    }
    
    0 讨论(0)
  • 2020-12-13 23:33

    http://msdn.microsoft.com/en-us/library/system.type.gettype.aspx

    Console.WriteLine("typeField is a {0}", typeField.GetType());
    

    which would give you something like

    typeField is a String
    
    typeField is a DateTime
    

    or

    http://msdn.microsoft.com/en-us/library/58918ffs(v=vs.71).aspx

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-13 23:41

    You can use for it the is operator. You can then check if object is specific type by writing:

    if (myObject is string)
    {
      DoSomething()
    }
    
    0 讨论(0)
提交回复
热议问题