Resharper:可能对标有 notnull 属性的实体进行 null 赋值
我在 response.GetResponseStream()
上收到此警告 我应该如何处理这个问题?
// Get response
using (var response = request.GetResponse() as HttpWebResponse)
{
// Get the response stream
if (response != null)
{
var reader = new StreamReader(response.GetResponseStream());
var responseString = reader.ReadToEnd();
return responseString;
}
}
为了清楚起见,基于一些误解的答案:
此行不是发生警告的位置:
using (var response = request.GetResponse() as HttpWebResponse)
此行是发生警告的位置:
var reader = new StreamReader(response.GetResponseStream());
I get this warning on response.GetResponseStream()
How should I handle this?
// Get response
using (var response = request.GetResponse() as HttpWebResponse)
{
// Get the response stream
if (response != null)
{
var reader = new StreamReader(response.GetResponseStream());
var responseString = reader.ReadToEnd();
return responseString;
}
}
For clarity based on some answers misinterpreting:
This line is not where the warning is occurring:
using (var response = request.GetResponse() as HttpWebResponse)
This line is where the warning is occurring:
var reader = new StreamReader(response.GetResponseStream());
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我怀疑 StreamReader 构造函数的参数具有 notnull 属性。请尝试以下操作:
I suspect
StreamReader
constructor's parameter has anotnull
attribute. Try the following:尝试缩短代码并将一次性资源包装在
using
语句中:甚至更进一步:
Try shortening your code and wrapping disposable resources in
using
statements:or even further:
如果
response
对象的类型为HttpWebRequest
,则响应将始终为HttpWebResponse
类型。如果不是,那就永远不会。要么你在错误的地方测试它(如果你可以传递由
WebRequest
派生的另一个类只是为了丢弃结果,为什么要调用.GetResponse()
)或测试不必要且没有效果。我猜 resharper 正在担心这一点,尽管在它下面进行了 null 测试。我会选择直接强制转换:
或者,考虑到您没有使用任何不是从
WebResponse
派生的HttpWebResponse
成员,根本不进行强制转换:If the
response
object is of typeHttpWebRequest
, then response will always be of typeHttpWebResponse
. If it's not, then it never will be.Either you're testing this at the wrong place (why call
.GetResponse()
if you could be passed another class derived byWebRequest
just to throw away the results) or testing unnecessary with no effect.I'm guessing resharper is worrying about that, despite the test for null below it. I'd go for either a direct cast:
Or, considering you aren't using any members of
HttpWebResponse
that isn't derived fromWebResponse
, no cast at all:您可以使用 C# 的 空条件运算符来消除警告:
它是一种语法糖,可以避免编写在运行时检查引用的空值的代码。在内部,这段代码相当于:
You can use C#'s null conditional operator to get rid of the warning:
It is a syntactic sugar to avoid writing code for checking null value of a reference at runtime. Internally this code is equivalent to :