当函数可以返回 MemoryStream 时,为什么我不能声明 MemoryStream 可空(MemoryStream?)?
我有一个返回 MemoryStream?
的函数。如果发生错误,则为 null。然后我发现无法声明变量MemoryStream?
public MemoryStream? GetResponseStream() { }
MemoryStream? stream = GetResponseStream();
类型“System.IO.MemoryStream”必须是不可为 null 的值类型,才能将其用作泛型类型或方法“System.Nullable”中的参数“T”
I have a function that returns MemoryStream?
. So null if there was an error that occurred. Then I found that I cannot declare a variable MemoryStream?
public MemoryStream? GetResponseStream() { }
MemoryStream? stream = GetResponseStream();
The type 'System.IO.MemoryStream' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'System.Nullable'
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
MemoryStream 是一个引用类型(使用
class
关键字),因此本身已经可以为空。只有值类型(使用struct
关键字声明)不可为 null,并且可以使用?
使其可为 null。因此,您的方法应如下所示:
并且您的方法调用如下所示:
顺便说一句:您可能需要考虑使用异常来表明
GetResponseStream
中发生了错误,而不是返回null
。MemoryStream is a reference type (declared with the
class
keyword) and therefore already is nullable by itself. Only value types (declared with thestruct
keyword) are non-nullable and can be made nullable with?
.So your method should look like this:
and your method call like this:
BTW: You might want to consider using exceptions to signal that an error occurred in
GetResponseStream
rather than returningnull
.MemoryStream
是一个引用类型,因此可以为 null。只有值类型才能成为Nullable
,因为否则不允许为它们分配 null 值。MemoryStream
is a reference type so can be null. Only value types can be made intoNullable<T>
because they are not allowed to be assigned a null value otherwise.只有值类型可以为 null,引用类型则不然。
MemoryStream
已经可以为 null,因此使其可为 null 没有意义Only value types can be nullable, not reference types. A
MemoryStream
can already be null, so it doesn't make sense to make it nullable不需要
?
,因为引用类型可以为null
。There is no need for
?
as reference types can benull
.可空修饰符 (?) 仅适用于值类型。流是一种对象类型,它始终可以设置为 null(就其本质而言,它已经是“可为空的”)。所以没有必要做你想做的事。
The nullable modifier (?) is for use only with value types. A stream is an object type, which can always be set to null ( it is. by its nature, already 'nullable'). So there is no need to o what you are trying to do.