当函数可以返回 MemoryStream 时,为什么我不能声明 MemoryStream 可空(MemoryStream?)?

发布于 2024-10-04 11:46:11 字数 330 浏览 0 评论 0原文

我有一个返回 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

木槿暧夏七纪年 2024-10-11 11:46:11

MemoryStream 是一个引用类型(使用 class 关键字),因此本身已经可以为空。只有值类型(使用 struct 关键字声明)不可为 null,并且可以使用 ? 使其可为 null。

因此,您的方法应如下所示:

public MemoryStream GetResponseStream() { ... }

并且您的方法调用如下所示:

MemoryStream stream = GetResponseStream();
if (stream == 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 the struct keyword) are non-nullable and can be made nullable with ?.

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.

烟沫凡尘 2024-10-11 11:46:11

MemoryStream 是一个引用类型,因此可以为 null。只有值类型才能成为 Nullable,因为否则不允许为它们分配 null 值。

MemoryStream is a reference type so can be null. Only value types can be made into Nullable<T> because they are not allowed to be assigned a null value otherwise.

寒冷纷飞旳雪 2024-10-11 11:46:11

只有值类型可以为 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

南街女流氓 2024-10-11 11:46:11

不需要 ?,因为引用类型可以为 null

public MemoryStream GetResponseStream()
{
    return(null);
}

There is no need for ? as reference types can be null.

public MemoryStream GetResponseStream()
{
    return(null);
}
§对你不离不弃 2024-10-11 11:46:11

可空修饰符 (?) 仅适用于值类型。流是一种对象类型,它始终可以设置为 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文