Sle*_*idi 11 c# generics struct class
假设我们有以下struct
使用泛型的定义:
public struct Foo<T>
{
public T First;
public T Second;
public Foo(T first)
{
this.First = first;
}
}
Run Code Online (Sandbox Code Playgroud)
编译说
在将控制权返回给调用者之前,必须完全分配'Foo.Second'
但是,如果Foo
是一个类,那么它会成功编译.
public class Foo<T>
{
public T First;
public T Second;
public Foo(T first)
{
this.First = first;
}
}
Run Code Online (Sandbox Code Playgroud)
为什么?为什么编译器对它们的区别对待?此外,如果在第一个中没有定义构造函数,Foo
那么它将编译.为什么会这样?
dri*_*iis 16
这是因为编译器规则强制在控制离开任何构造函数之前必须分配结构中的所有字段.
您可以通过执行以下操作来使代码正常工作:
public Foo(T first)
{
this.First = first;
this.Second = default(T);
}
Run Code Online (Sandbox Code Playgroud)
另请参阅为什么必须使用非默认构造函数初始化C#结构中的所有字段?
Jon*_*n B 11
这是整体结构的要求 - 它与泛型无关.构造函数必须为所有字段赋值.
请注意,此处发生相同的错误:
struct Foo
{
public int A;
public int B;
public Foo()
{
A = 1;
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
19443 次 |
最近记录: |