检查类的类型

本文关键字:类型 检查 | 更新日期: 2023-09-27 17:49:27

我有以下c#类:

public class Reply<T> { }
public class Ok<T> : Reply<T> { }
public class BadRequest<T> : Reply<T> { }

在接收Reply的方法上,我需要检查它的类型是Ok或BadRequest或…比如:

public static String Evaluate(Reply<T> reply) {
  switch (typeof(reply)) {
    case typeof(Ok<T>):
      // Do something
      break;
    // Other cases
  }
}

但是我得到了错误

 The type or namespace name 'reply' could not be found (are you missing a using directive or an assembly reference?)

知道如何测试回复的类型吗?

检查类的类型

嗯,typeof()只适用于类型(与typeof(int)一样),而不是变量,所以您需要

reply.GetType() 

但是你会发现case表达式需要文字值,所以你需要转换成if-else块:
public static String Evaluate<T>(Reply<T> reply) {
    if(reply.GetType() == typeof(Ok<T>)) {
        // Do something
    }
    else {
     // Other cases  
    }
}  

  if(reply is Ok<T>) {
      // Do something
  }
  else {
      // Other cases
  }  

reply.GetType()是您正在寻找的

您可以使用typeof,这是一个返回对象的System.Type的操作符

https://msdn.microsoft.com/en-us/library/58918ffs.aspx