简体   繁体   English

C#中的类型推理规则?

[英]Type inference rules in C#?

I read the following MSDN page, which states the following interesting thing:我阅读了以下MSDN 页面,其中说明了以下有趣的事情:

The first rule is that the var declaration follows the normal type inference rules: The type is inferred to be the static type of the switch expression.第一条规则是 var 声明遵循正常的类型推断规则:类型被推断为 switch 表达式的 static 类型。 From that rule, the type always matches.根据该规则,类型始终匹配。

Nowhere in MSDN could I find a reference to the so-called "normal type inference rules", and why does var used in that sense infer to the static type of the switch expression?在 MSDN 中,我找不到对所谓“正常类型推理规则”的引用,为什么在这个意义上使用的var会推断出开关表达式的 static 类型?

Perhaps I don't know what a static type is.也许我不知道static类型是什么。 I know what the static keyword does, but I don't think that's what's happening in the switch expression.我知道static关键字的作用,但我不认为这就是 switch 表达式中发生的事情。

C# is a statically typed language, meaning that types must be known at compile-time, and the type assigned to a variable cannot change at runtime. C# 是一种静态类型语言,这意味着在编译时必须知道类型,并且分配给变量的类型在运行时不能更改。 Consider first that all of the following lines result in exactly the same thing:首先考虑以下所有行的结果完全相同:

int x = 123;
System.Int32 x = 123;
var x = 123;
  • int is just an alias for System.Int32 int只是System.Int32的别名
  • The compiler infers that x is of type System.Int32 when using var because it's been assigned an integral number.编译器在使用var推断xSystem.Int32类型,因为它被分配了一个整数。

What you can't do with C# that you can do in dynamically typed languages (like javaScript) is this: C#不能动态类型语言(如 javaScript)做的事情是:

var x = 123;
x = "Hello world";

In C# the compiler will complain that you cannot assign a string to an int variable, but JavaScript, being a dynamic language will allow it.在 C# 中,编译器会抱怨您不能将字符串分配给 int 变量,但是 JavaScript,作为一种动态语言将允许它。

Perhaps I don't know what a static type is.也许我不知道static类型是什么。 I know what the static keyword does, but I don't think that's what's happening in the switch expression.我知道static关键字的作用,但我不认为这就是 switch 表达式中发生的事情。

In the example that you have linked, by " static type of the switch expression " they are referring to the type of the variable shapeDescription - eg type string .在您链接的示例中,通过“开关表达式的 static 类型”,它们指的是变量shapeDescription的类型 - 例如类型string

In other words, following " normal type inference rules " - the var o also has type string .换句话说,遵循“普通类型推断规则” - var o也有类型string

static object CreateShape(string shapeDescription)
{
    switch (shapeDescription)
    {
        // removed for conciness

        case var o when (o?.Trim().Length ?? 0) == 0:
            // white space
            return null;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM