[英]Check properties of object is null
我有“相册List
”对象(例如相册)。 我检查对象的属性为null。
只是例子:
if (albums.Last() != null
&& albums.Last().Photos != null
&& albums.Last().Photos.Description != null) { //action }
我可以在代码中缩短检查时间吗?
只需将其包装在一个函数中:
public static bool IsInitialized(a Album) {
return a != null &&
a.Photos != null &&
a.Photos.Description != null;
}
然后,您的调用代码将变为:
var album = albums.LastOrDefault();
if (Album.IsInitialized(album)) {
// its fine
}
你不能
顺便说一句:
使用vars而不是一直都调用函数( Last()
)。
使用LastOrDefault()
并防止崩溃。
var lastAlbum = albums.LastOrDefault(); if(lastAlbum != null && lastAlbum.Photos != null && lastAlbum.Photos.Description != null){//action}
您可以使用扩展方法-
public static class ListExtension {
public static bool IsLastPhotoNotNull(this List<Album> albums){
var album = albums.LastOrDefault();
return album != null && album.Photos != null && album.Photos.Description != null;
}
}
然后用列表调用它
List<Album> albums;
if(!albums.IsLastPhotoNotNull()){
//...do other actions
}
简短一点 但是效率更高,是的。
您多次调用Last()
方法。 如果该调用中涉及数据库操作,则可能会损害性能。
将方法拉出if
之外:
var last = albums.Last();
if (last != null
&& last.Photos != null
&& last.Photos.Description != null)
{ //action }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.