c# - 在 C# 中,如何在运行时检查对象是否属于某种类型?

标签 c# object types

在 C# 中如何在运行时检查对象是否属于特定类型?

最佳答案

您可以使用is 关键字。例如:

using System; 

class CApp
{
    public static void Main()
    { 
        string s = "fred"; 
        long i = 10; 

        Console.WriteLine( "{0} is {1}an integer", s, (IsInteger(s) ? "" : "not ") ); 
        Console.WriteLine( "{0} is {1}an integer", i, (IsInteger(i) ? "" : "not ") ); 
    }

    static bool IsInteger( object obj )
    { 
        if( obj is int || obj is long )
            return true; 
        else 
            return false;
    }
} 

产生输出:

fred is not an integer 
10 is an integer

关于c# - 在 C# 中,如何在运行时检查对象是否属于某种类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3401447/

相关文章:

c# - 图像编码为 ccitt 的 iOS pdf

c# - 将对象转换为对象数组

c# - 合并基类和派生 C# 类的工具

php - 通过链接导航多个对象而不重复

python - 在 Celery 任务中获取 task_id

javascript - 如何判断一个javascript变量的数据类型是Array?

c - 在数组中存储 volatile 字符

types - 如何确定neo4j中节点内的属性值类型?

c# - 此测试中的多个断言是否错误?

javascript - 根据选定的嵌套复选框生成 JSON