这里我下载了GetSourceAttachment方法的word文件.当这个方法返回空字节然后我的字节附件数组给出一个错误(对象引用没有设置对象的实例).当我在条件中检查附件的长度然后它给出错误.任何人都可以帮我默认初始化字节数组然后检查长度.
try
{
byte[] Attachment = null ;
string Extension = string.Empty;
ClsPortalManager objPortalManager = new ClsPortalManager();
Attachment = objPortalManager.GetSourceAttachment(Convert.ToInt32(hdnSourceId.Value), out Extension);
if (Attachment.Length > 0 && Attachment != null)
{
DownloadAttachment("Attacment", Attachment, Extension);
}
else
{
ClientScript.RegisterStartupScript(typeof(Page), "SymbolError", "<script type='text/javascript'>alert('Attachment is not Uploaded !');</script>");
}
}
catch
{
}
Run Code Online (Sandbox Code Playgroud)
Son*_*nül 74
做就是了
if (Attachment != null && Attachment.Length > 0)
Run Code Online (Sandbox Code Playgroud)
来自&&运营商
条件AND运算符(&&)执行其bool操作数的逻辑AND,但仅在必要时才计算其第二个操作数.
Mat*_*son 16
您必须交换测试的顺序:
从:
if (Attachment.Length > 0 && Attachment != null)
Run Code Online (Sandbox Code Playgroud)
至:
if (Attachment != null && Attachment.Length > 0 )
Run Code Online (Sandbox Code Playgroud)
第一个版本首先尝试取消引用Attachment,因此如果它为null则抛出.第二个版本将首先检查空值,并且只检查长度是否为空(由于"布尔短路").
Met*_*lay 13
.Net V 4.6或C#6.0
试试这个
if (Attachment?.Length > 0)
Run Code Online (Sandbox Code Playgroud)
你的支票应该是:
if (Attachment != null && Attachment.Length > 0)
Run Code Online (Sandbox Code Playgroud)
首先检查附件是否为空,然后长度,因为您正在使用&&它将导致短路评估
条件AND运算符(&&)执行其bool操作数的逻辑AND,但仅在必要时才计算其第二个操作数.
以前你有类似的条件:(Attachment.Length > 0 && Attachment != null),因为第一个条件是访问属性Length,如果Attachment是null,你最终得到异常,在修改条件的情况下(Attachment != null && Attachment.Length > 0),它将首先检查null,如果Attachment不为null则仅进一步移动.