在struct vs类中使用的泛型
假设我们有以下使用泛型的 struct
定义:
Assume that we have the following struct
definition that uses generics:
public struct Foo<T>
{
public T First;
public T Second;
public Foo(T first)
{
this.First = first;
}
}
编译器说
'Foo.Second'必须在控制权返回给调用者之前完全分配
'Foo.Second' must be fully assigned before control is returned to the caller
但是,如果 Foo
是一个类,那么它会成功编译。
However, if Foo
is a class, then it compiles successfully.
public class Foo<T>
{
public T First;
public T Second;
public Foo(T first)
{
this.First = first;
}
}
为什么?为什么编译器对它们有不同的看法?此外,如果在第一个 Foo
中没有定义构造函数,那么它将编译。为什么是这种行为?
Why? Why the compiler treats them differently? Moreover if no constructor is defined in the first Foo
then it compiles. Why this behaviour?
这是因为编译器规则强制在结构中的所有字段必须在控制之前分配任何构造函数
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);
}