我有以下代码:
T imageCollectionItem;
// This checks if image actually exists, if it doesn't it gets the next best one... Thumbnail wil always exist so it will always find one
imageCollectionItem = (this.ResizedImageCollection
.Where(x => ((IBaseImage)x).Image.ImageSizeType.Key != ImageSizeType.Original)
.OrderByDescending(x => ((IBaseImage)x).Image.ImageSizeType.Key == imageSizeTypeKey)
.ThenBy(x => ((IBaseImage)x).Image.ImageSizeType.Order)
.FirstOrDefault());
if( imageCollectionItem != null )
{
return ((IBaseImage)imageCollectionItem).Image; // Compiles fine
return (IBaseImage)imageCollectionItem.Image; // Fails
}
(cast)variable
和((cast)variable)
有什么区别?考虑一个编译而一个不编译?
最佳答案
if( imageCollectionItem != null )
{
return ((IBaseImage)imageCollectionItem).Image; // Compiles fine
return (IBaseImage)imageCollectionItem.Image; // Fails
}
第一行运行是因为
.Image
在已强制转换为正确接口的对象上运行。在第二行中,直到调用
.Image
属性后,您才进行强制转换-我认为这会导致“找不到成员”错误或类似错误。关于c# - (cast)变量和((cast)变量)有什么区别,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29627754/