C# struct vs class 中使用的泛型
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13731798/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Generics used in struct vs class
提问by Sleiman Jneidi
Assume that we have the following structdefinition that uses generics:
假设我们有以下struct使用泛型的定义:
public struct Foo<T>
{
public T First;
public T Second;
public Foo(T first)
{
this.First = first;
}
}
The compiler says
编译器说
'Foo.Second' must be fully assigned before control is returned to the caller
'Foo.Second' 必须在控制返回给调用者之前完全赋值
However, if Foois a class, then it compiles successfully.
但是,如果Foo是一个类,那么它编译成功。
public class Foo<T>
{
public T First;
public T Second;
public Foo(T first)
{
this.First = first;
}
}
Why? Why the compiler treats them differently? Moreover if no constructor is defined in the first Foothen it compiles. Why this behaviour?
为什么?为什么编译器对它们的处理方式不同?此外,如果在第一个中没有定义构造函数,Foo则它会编译。为什么会有这种行为?
采纳答案by driis
That is because a compiler rule enforces that all fields in a struct must be assigned before control leaves any constructor.
这是因为编译器规则强制要求必须在控制离开任何构造函数之前分配结构中的所有字段。
You can get your code working by doing this:
你可以通过这样做让你的代码工作:
public Foo(T first)
{
this.First = first;
this.Second = default(T);
}
Also see Why Must I Initialize All Fields in my C# struct with a Non-Default Constructor?
回答by Jon B
That's a requirement of structs in general -- it has nothing to do with generics. Your constructor must assign a value to all fields.
这是一般结构的要求——它与泛型无关。您的构造函数必须为所有字段赋值。
Note the same error happens here:
请注意,这里发生了同样的错误:
struct Foo
{
public int A;
public int B;
public Foo()
{
A = 1;
}
}
回答by SergeyS
Because it is a rule in C# that all fields must be assigned for structs (inline or in constructor). This is because of a struct nature. It has nothing about generic it or not generic.
因为 C# 中的规则是必须为结构分配所有字段(内联或在构造函数中)。这是因为结构性质。它与通用或不通用无关。
回答by Jeff
The other answers explain the behaviour correctly, but neglect to mention the second part of your question, so here it is for completion.
其他答案正确解释了行为,但忽略了问题的第二部分,所以在这里完成。
When you don't explicitly define a constructor, the compiler will produce a default constructor which assigns default values (e.g. nullfor objects, 0for numbers etc.) to every field.
当您没有明确定义构造函数时,编译器将生成一个默认构造函数,该构造函数为每个字段分配默认值(例如null,对象、0数字等)。

