3

我有一个返回的函数MemoryStream?。如果发生错误,则为 null。然后我发现我不能声明一个变量MemoryStream?

public MemoryStream? GetResponseStream() { }
MemoryStream? stream = GetResponseStream();

类型“System.IO.MemoryStream”必须是不可为空的值类型,才能将其用作泛型类型或方法“System.Nullable”中的参数“T”

4

5 回答 5

16

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

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

public MemoryStream GetResponseStream() { ... }

你的方法调用是这样的:

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

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

于 2010-11-22T14:34:46.440 回答
1

MemoryStream是引用类型,因此可以为空。只能做成值类型Nullable<T>,否则不允许为它们分配空值。

于 2010-11-22T14:35:06.830 回答
0

只有值类型可以为空,而不是引用类型。AMemoryStream已经可以为空,所以让它可以为空是没有意义的

于 2010-11-22T14:35:07.863 回答
0

不需要?as 引用类型即可null

public MemoryStream GetResponseStream()
{
    return(null);
}
于 2010-11-22T14:35:33.473 回答
0

可空修饰符 (?) 仅用于值类型。流是一种对象类型,它始终可以设置为 null(它本质上已经是“可空的”)。所以没有必要做你想做的事。

于 2010-11-22T14:36:35.993 回答