gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 13:13:48 27 4
gpt4 key购买 nike

我有一个返回 MemoryStream? 的函数。如果发生错误,则为 null。然后发现不能声明变量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'

最佳答案

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

所以你的方法应该是这样的:

public MemoryStream GetResponseStream() { ... }

你的方法调用是这样的:

MemoryStream stream = GetResponseStream();
if (stream == null) { ... }

顺便说一句:您可能需要考虑使用异常来表示 GetResponseStream 中发生了错误,而不是返回 null

关于c# - 当函数可以返回 MemoryStream 时,为什么我不能声明 MemoryStream 可为空(MemoryStream?)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4246479/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com