C# 类型判断

类型判断

  • 1. 类型判断用到的运算符
  • 2. 类型判断实例

1. 类型判断用到的运算符

  • sizeof 运算符可以获知数据类型在内存中占用几个字节;
  • typeof 运算符可以获取数据类型的 CTS 类型名;
  • GetType() 方法可以获得变量的数据类型;
  • is 运算符检验某个对象是否为某种类型,用法更为简洁;

2. 类型判断实例

using System;

namespace TypeJudge
{
    class Program
    {
        static void Main(string[] args)
        {
            #region sizeof 运算符
            //通过 sizeof 运算符可以获知数据类型在内存中占用几个字节。
            Console.WriteLine("int: " + sizeof(int));
            Console.WriteLine("long: " + sizeof(long));
            Console.WriteLine("float: " + sizeof(float));
            Console.WriteLine("double: " + sizeof(double));
            Console.WriteLine("char: " + sizeof(char));
            Console.WriteLine();
            #endregion
    
            #region typeof 运算符
            //通过 typeof 运算符可以获取数据类型的 CTS 类型名。
            Console.WriteLine("int: " + typeof(int));
            Console.WriteLine("long: " + typeof(long));
            Console.WriteLine("float: " + typeof(float));
            Console.WriteLine("double: " + typeof(double));
            Console.WriteLine("char: " + typeof(char));
            Console.WriteLine();
            #endregion

            #region GetType()方法
            int n = 10;
            double f = 3.14;
            string s = "Good!";
            Cat kitty = new Cat();
            Human jack = new Human();
            Console.WriteLine("n: " + n.GetType());
            Console.WriteLine("f: " + f.GetType());
            Console.WriteLine("s: " + s.GetType());
            Console.WriteLine("kitty: " + kitty.GetType());
            Console.WriteLine("jack: " + jack.GetType());

            //判断kitty是不是猫有以下两种方法,第二种方法更简洁
            if(kitty.GetType() == typeof(Cat))
                Console.WriteLine("Kitty is a cat.");
            else
                Console.WriteLine("Kitty is not a cat.");

            if(kitty is Cat)
                Console.WriteLine("Kitty is a cat.");
            else
                Console.WriteLine("Kitty is not a cat.");

            //Kitty既然是猫,那它当然也是哺乳动物了
            if (kitty is Mammal)
                Console.WriteLine("Kitty is a Mammal.");
            else
                Console.WriteLine("Kitty is not a Mammal.");
            #endregion
        }
    }
    class Mammal
    {
    }
    class Cat: Mammal
    {
    }
    class Human : Mammal
    {
    }
}

C# 类型判断_第1张图片

你可能感兴趣的:(C#,c#,开发语言,后端)