空检查扩展方法
因此,我在应用程序中执行了大量数据库工作 - 并且我的缓存系统有几种可能的返回值。它可以返回 null,可以返回默认值(类型),也可以返回无效对象(无效对象,我的意思是具有不正确属性/值的对象)。我想创建一个扩展方法来为我进行所有这些检查,如下所示:
public static bool Valid<T> (this T obj) where T: class
{
if (obj == null)
return false;
else if (obj == default(T))
return false;
//Other class checks here
else
return true;
}
问题是,我的编译器告诉我 if (obj == default(T))
将始终为 false。
这是为什么?
So, I'm doing a lot of database work in an application - and there are several possible return values of my caching system. It can return null, it can return a default (type) or it can return an invalid object (by invalid object, I mean one with incorrect properties / values). I want to create an extension method to make all those checks for me, like so:
public static bool Valid<T> (this T obj) where T: class
{
if (obj == null)
return false;
else if (obj == default(T))
return false;
//Other class checks here
else
return true;
}
The problem is, my compiler is telling me that if (obj == default(T))
will always be false.
Why is that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
由于您有“类”约束(
where T: class
),因此default(T)
始终 等于 null。您已经在原始 if 语句中对此进行了检查,因此第二种情况 (obj == default(T)
) 永远不可能为真。Since you have a "class" constraint (
where T: class
),default(T)
is always equal to null. You already have a check for that in the original if statement, so the second case (obj == default(T)
) could never be true.我不确定你将其限制在课堂上是因为你想要还是因为你觉得必须这样做。如果是后者,这里有一种对复杂和简单类型进行默认值检查的方法:
如果您选择将其限制为仅类是有意的或出于业务案例,请随意忽略此建议。这可能无法解释的另一件事是简单类型的装箱(尽管这些天我通常使用可空的简单类型,这段代码确实适用)。
I'm not sure if you are constraining it to class because you want to or because you feel you have to. If it's the latter, here is a way to do default value checking on complex and simple types:
If your choice to constrain it to class only was intentional or for a business case, feel free to ignore this suggestion. Another thing this may not account for is boxing of simple types (although I usually use nullable simple types these days, which this code does work for).
您需要做出的第一个决定是:T 可以是像 int 这样的值类型吗?
如果是这样,您可以删除
,
如果 T 始终是引用类型,您可以删除
The first decision you need to make is: Can T be a value type like int?
If so you can remove
and
If T is always a reference type you can remove