使用未分配的局部变量:值类型与自定义结构 [英] Use of unassigned local variable: value type vs custom struct

查看:61
本文介绍了使用未分配的局部变量:值类型与自定义结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

原始C#值类型,例如 int 是一种结构.那么,为什么未初始化 int 呢?我认为应该有默认的构造函数.另一方面,可以使用自定义结构.

A primitive C# value type, for example int is a struct. So, why is int not initialized? There supposed to be default constructor, I think. On the other hand, a custom struct is ok.

在以下代码中

struct STRCT { }
class Program
{
    static void Main(string[] args)
    {
        STRCT strct;
        strct.Equals(8);
        strct.GetHashCode();
        strct.GetType();
        strct.ToString();

        int i;
        i.Equals(8);
        i.GetHashCode();
        i.GetType();
        i.ToString();
    }
}

在C#编译器视图中可以确定前5行代码,而后5行代码会产生编译错误:

while first 5 lines of code are ok from the C# compiler view, next 5 lines of code generates compile error:

使用未分配的局部变量

use of unassigned local variable

请解释原因?从我的角度来看,这两种类型都是结构,并且应具有相同的行为.

Please, explain why? From my point of view both types are structs and shall have the same behavior.

推荐答案

这是确定分配"规则的极端病理现象.具体来说:

It's a pathological extreme of the rules of Definite Assignment. Specifically:

如果认为每个结构体变量的实例变量都已明确分配,则认为该结构类型变量已明确分配.

A struct-type variable is considered definitely assigned if each of its instance variables is considered definitely assigned.

在这种情况下( STRCT strct ),实例变量集为空,因此确实已经对它们全部进行了赋值.

In this case (STRCT strct), the set of instance variables is empty, and so it is true that they've all been definitely assigned.

这篇关于使用未分配的局部变量:值类型与自定义结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆