我正在编写C#程序,而VisualStudio的VSTO向导会生成以下代码.
private static string GetResourceText(string resourceName)
{
Assembly asm = Assembly.GetExecutingAssembly();
string[] resourceNames = asm.GetManifestResourceNames();
for (int i = 0; i < resourceNames.Length; ++i)
{
if (string.Compare(resourceName, resourceNames[i], StringComparison.OrdinalIgnoreCase) == 0)
{
using (StreamReader resourceReader = new StreamReader(asm.GetManifestResourceStream(resourceNames[i])))
{
if (resourceReader != null)
{
return resourceReader.ReadToEnd();
}
}
}
}
return null;
}
Run Code Online (Sandbox Code Playgroud)
我认为 if (resourceReader != null)是多余的,因为构造函数总是返回非null.不是吗?
在常规的理智代码中,构造函数不会返回null.这里有一些令人费解的方法,你可以强制构造函数返回null,但就是这样一个奇怪的边缘情况下,你将永远看不到它.对于所有意图和目的:new在这个对象永远不会返回null- 并且在a之后添加一个null-check是完全没有意义的new(),特别是对于明智的事情StreamReader.
一个简单的例子,你可以得到null:
object obj = new int?()
Run Code Online (Sandbox Code Playgroud)
但这只是暴露了可空类型的微妙拳击行为.获取构造函数返回的更复杂方法null需要恶意:
static void Main() {
var obj = new MyFunnyType(); // wow! null!
}
class MyFunnyProxyAttribute : ProxyAttribute {
public override MarshalByRefObject CreateInstance(Type serverType) {
return null;
}
}
[MyFunnyProxy]
class MyFunnyType : ContextBoundObject { }
Run Code Online (Sandbox Code Playgroud)