C#类型推断

Step1/API/TypeInference.cs

using System;

namespace Step1.API
{
    class TypeInference
    {
        public static void PrintType()
        {
            var a = 10;
            var b = 10.23;
            var c = "Hello";
            var d = false;

            Console.WriteLine("a:"+a.GetType());
            Console.WriteLine("b:" + b.GetType());
            Console.WriteLine("c:" + c.GetType());
            Console.WriteLine("d:" + d.GetType());
            Console.WriteLine();
        }
    }
}

Step1/Run.cs

using System;
using Step1.API;
namespace Step1
{
    class Run
    {
        public static  int Main(String[] args)
        {
            //helloworld.printhello();
            TypeInference.PrintType();
            return 0;
        }
    }
}

运行结果
a:System.Int32
b:System.Double
c:System.String
d:System.Boolean

需要遵循一些规则:

  • 变量必须初始化。否则,编译器就没有推断变量类型的依据。
  • 初始化器不能为空。
  • 初始化器必须放在表达式中。
  • 不能把初始化器设置为一个对象,除非在初始化器中创建了一个新对象。

猜你喜欢

转载自blog.csdn.net/Aikihny/article/details/80041431