gpt4 book ai didi

c# - 检查类的类型

转载 作者:太空宇宙 更新时间:2023-11-03 19:59:09 24 4
gpt4 key购买 nike

我有以下 C# 类:

public class Reply<T> { }

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

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

在接收回复的方法上,我需要检查它的类型是 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 block :

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
}

关于c# - 检查类的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30260932/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com