在struct vs类中使用的泛型 [英] Generics used in struct vs class
问题描述
假设我们有以下使用泛型的 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);
}
这篇关于在struct vs类中使用的泛型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!