[英]Why can't I declare a MemoryStream nullable (MemoryStream?) when a function can return MemoryStream?
I have a function that returns MemoryStream?
我有一个返回
MemoryStream?
的函数MemoryStream?
. 。 So null if there was an error that occurred.
如果发生错误,则为null。 Then I found that I cannot declare a variable
MemoryStream?
然后我发现我无法声明一个变量
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'
类型'System.IO.MemoryStream'必须是非可空值类型才能在泛型类型或方法'System.Nullable'中将其用作参数'T'
MemoryStream is a reference type (declared with the class
keyword) and therefore already is nullable by itself. MemoryStream是一个引用类型(使用
class
关键字声明),因此它本身已经可以为空。 Only value types (declared with the struct
keyword) are non-nullable and can be made nullable with ?
只有值类型(使用
struct
关键字声明)是不可为空的,并且可以使用可为空的?
. 。
So your method should look like this: 所以你的方法应该是这样的:
public MemoryStream GetResponseStream() { ... }
and your method call like this: 你的方法调用如下:
MemoryStream stream = GetResponseStream();
if (stream == null) { ... }
BTW: You might want to consider using exceptions to signal that an error occurred in GetResponseStream
rather than returning null
. 顺便说一句:您可能需要考虑使用异常来表示
GetResponseStream
发生错误而不是返回null
。
MemoryStream
is a reference type so can be null. MemoryStream
是一个引用类型,因此可以为null。 Only value types can be made into Nullable<T>
because they are not allowed to be assigned a null value otherwise. 只能将值类型设置为
Nullable<T>
,否则不允许为它们分配空值。
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 MemoryStream
已经可以为null,因此将其设置为可空是没有意义的
There is no need for ?
没有必要
?
as reference types can be null
. 因为引用类型可以为
null
。
public MemoryStream GetResponseStream()
{
return(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').
流是一种对象类型,它总是可以设置为null(从本质上讲,它已经是'可空')。 So there is no need to o what you are trying to do.
所以你不需要做什么。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.