我有下一个代码:
class GenericStruct<T> where T : struct
{
public void M()
{
T temp1;
T temp2;
string s = temp1.ToString();
Type t = temp1.GetType();
bool b = temp1.Equals(temp2);
}
}
我在调用方法时遇到了两个错误“使用未分配的局部变量”:ToString和Equals,但GetType没问题。 存在的“打扰”我的事实是
where T : struct
但是,如果我写道:
struct NotGenericStruct
{
public void M()
{
NotGenericStruct temp1;
NotGenericStruct temp2;
string s = temp1.ToString();
Type t = temp1.GetType();
bool b = temp1.Equals(temp2);
}
}
没问题,编译时没有错误。 我理解,struct数据类型具有默认构造函数,并且所有成员都已初始化,因此不需要编写显式new。
两个代码和平的区别究竟是什么?请解释我的不解之处
由于
答案 0 :(得分:1)
声明
class GenericStruct<T> where T : struct
struct
表示T
是按值类型。
type参数必须是值类型。可以指定除
Nullable
之外的任何值类型。
因此,T
可以是int
。在这种情况下声明
T temp1;
离开temp1
未初始化。
答案 1 :(得分:1)
这两段代码之间的行为差异的原因在于,在通用情况下,我们所知道的是T是结构。除此之外,我们不能做出任何更多的假设。我们不知道结构是否包含方法,字段,属性,构造函数或其他任何内容。
在第二种情况下,我们知道结构类型为NotGenericStruct
,我们知道有关此结构的所有信息。特别是我们可以看到它所拥有的只是一种方法。这意味着我们知道实际上没有需要在此对象上初始化的状态。
我无法引用允许这样做的langauge规范的确切部分,但很明显看到编译器允许一个整体结构,因为它知道它与完成new NotGenericStruct
完全相同。
很容易看出行为上的差异,因为如果你向NotGenericStruct
添加一个int字段(或任何其他类型),那么它会立即开始抱怨使用未初始化的局部变量(参考{{1现在它有字段)。
一般情况下,这是一个非常特殊的情况,仅适用于没有字段的结构。任何具有需要字段的类或任何结构都要初始化,因此通常最好和最简单地假设所有本地需要初始化。它肯定可能产生更易读的代码。
答案 2 :(得分:0)
尝试:
class GenericStruct<T> where T : struct
{
public void M()
{
T temp1 = default(T);
T temp2 = default(T);
string s = temp1.ToString();
Type t = temp1.GetType();
bool b = temp1.Equals(temp2);
}
}