由于C# 4中修复了一个错误,下面的程序打印true
。(在LINQPad中试用)
void Main() { new Derived(); }
class Base {
public Base(Func<string> valueMaker) { Console.WriteLine(valueMaker()); }
}
class Derived : Base {
string CheckNull() { return "Am I null? " + (this == null); }
public Derived() : base(() => CheckNull()) { }
}
在处于发布模式的VS2008中,它抛出一个InvalidProgramException。(在调试模式下,它可以正常工作)
在VS2010 Beta2中,它不能编译(我没有尝试Beta1);我以一种艰难的方式了解到这一点
有没有其他方法可以用纯C#来制作this == null
?
发布于 2009-10-21 21:08:02
我受够了!(也得到了证据)
发布于 2009-10-21 20:59:32
我可能错了,但我很确定如果你的对象是null
,就不会有this
应用的场景。
例如,如何调用CheckNull
Derived derived = null;
Console.WriteLine(derived.CheckNull()); // this should throw a NullReferenceException
发布于 2010-05-08 00:16:40
不确定这是否是你要找的
public static T CheckForNull<T>(object primary, T Default)
{
try
{
if (primary != null && !(primary is DBNull))
return (T)Convert.ChangeType(primary, typeof(T));
else if (Default.GetType() == typeof(T))
return Default;
}
catch (Exception e)
{
throw new Exception("C:CFN.1 - " + e.Message + "Unexpected object type of " + primary.GetType().ToString() + " instead of " + typeof(T).ToString());
}
return default(T);
}
示例: UserID = CheckForNull(Request.QueryString"UserID",147);
https://stackoverflow.com/questions/1600662
复制相似问题