默认值(t?)不会返回null t时t是值类型
我遇到了以下现象,绝对是bmog乱的。我正在使用启用无效的C#10。
默认值(int?)
按预期返回null。但是,以下函数返回默认(t)
public static T? ShouldReturnNull<T>()
{
return default(T?);
}
在 shore shore returnnull&lt; int&gt;()
的情况下我们得到0。是否也应该返回null吗?
我的程序中有以下代码,其中这将成为一个问题:
public T?[] FindKElements(...)
{
var result = new (T, double)?[k];
// ... populate result array,
// possibly including null values...
// return an array containing only the T part or null
return result.Select(e => e is null ? default(T?) : e.Value.Item1).ToArray();
}
有没有办法将其保留为通用,但是当t是一个值类型时,请使用适当的nulls?编译器不会让我使用 null
代替默认(t?)
。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在没有
的情况下,其中t:struct
约束,t?
不是 Meannullable&lt; t&gt;
;它的意思是“t
,但请注意,它不会在NRT Sense中是null
- 并且由于NRT NULLS 从不将其应用于您的值-Type方案:基本上仅表示t
;值类型t
的默认值不是null
(从任何意义上讲)。在您需要的“ null检查”的情况下通常要忘记
nullable&lt; t&gt;
,只是跟踪:bool
),t
)单独,明确;这可以通过:
bool somemethod(out var t)
(hasvalue:bool:bool,value:t)somemethod()
也许&lt; t&gt; t&gt; somemethod()
(其中
也许&lt; t&gt;
只是由bool Hasvalue
和astruct > t值)
这有效地创建了类似于
nullable&lt; t&gt;
的东西,但是无论类型如何,它都适用于所有值。不用检查null,只需先检查.hasvalue
,并且如果true ,则假定该值有意义。In the absence of a
where T : struct
constraint,T?
does not meanNullable<T>
; it means "T
, but note that it won't benull
in the NRT sense" - and since NRT nulls never apply to your value-type scenario: it basically just meansT
; and the default value of a value-typeT
is notnull
(in any sense).In the scenario where you need "null checking" that crosses both value-type and reference-type scenarios including support for value-types without a value, then the easiest approach is usually to forget about
Nullable<T>
and just track:bool
), andT
)separately, and explicitly; this could be via any of:
bool SomeMethod(out var T)
(HasValue: bool, Value: T) SomeMethod()
Maybe<T> SomeMethod()
(where
Maybe<T>
is just a customstruct
that is composed of abool HasValue
and aT Value
)This is effectively creating something akin to
Nullable<T>
, but which applies to all values, regardless of type. Instead of checking for null, just check.HasValue
first, and if true, assume that the value is meaningful.