我加了这个,希望能够多一点 light由Jon和Marc提供的答案。
考虑这种非泛型方法:
public static void SetToNull(ref ISomeInterface obj) {
obj = null;
}
嗯...设置ref
参数设置为null。这只适用于参考类型,对吗? (嗯,或者对于Nullable<T>
;但是让我们忽略这种情况以使事情变得简单)。因此,此方法编译的事实告诉我们,声明为某种接口类型的变量必须被视为引用类型。
关键短语这里“声明”:考虑这个试图调用上述方法:
var x = new SomeStruct();
// This line does not compile:
// "Cannot convert from ref SomeStruct to ref ISomeInterface" --
// since x is declared to be of type SomeStruct, it cannot be passed
// to a method that wants a parameter of type ref ISomeInterface.
SetToNull(ref x);
当然,你不能在上面的代码通过x
到SetToNull
原因是x
会需要声明为ISomeInterface
您能够通过ref x
和而不是,因为编译器神奇地知道SetToNull
包含行obj = null
。但是,仅仅加强我的观点的方式:在obj = null
线是合法正是因为这将是非法传递变量不声明为ISomeInterface
的方法。
换句话说,如果一个变量声明为ISomeInterface
,它可以设置为空,纯粹和简单。这是因为接口是引用类型 - 因此,将对象声明为接口并将其分配给值类型的值对象框。
现在,在另一方面,考虑这个假设的泛型方法:
// This method does not compile:
// "Cannot convert null to type parameter 'T' because it could be
// a non-nullable value type. Consider using 'default(T)' instead." --
// since this method could take a variable declared as, e.g., a SomeStruct,
// the compiler cannot assume a null assignment is legal.
public static void SetToNull<T>(ref T obj) where T : ISomeInterface {
obj = null;
}
我假设。不完全确定是什么让我怀疑会是这样。只是以为我会把它扔出去,以防万一别人有奇怪的想法。 – Sekhat 2010-06-13 15:51:46
给男人一个工具来获得答案(红门反射器),他会有生命的答案。但给他一个答案,他会回来更多的问题和更多的SO重点... – 2010-06-13 17:24:27
@Ben:另一方面,给男人一个工具,他们将不得不每次检查它,不确定。给一个男人一个解释*,他们可以为自己推理一下。 – 2010-06-13 17:39:04