如何解决指示泛型类型在某些情况下可以为 null 的属性
我正在编写一个具有不受约束的泛型参数的泛型类。到目前为止,我已经解决了
-
[AllowNull]
表示输入参数可能为空 -
[MaybeNull]
表示输出参数可能为空 -
[return: MaybeNull]
表示方法的返回值可能为 null(它对属性 getter 没有影响!)
属性上的 -
[MaybeNull]
表示 getter 可以返回 null(不影响 setter)
属性上的 -
[AllowNull]
表示 setter 接受 null(它不影响 getter)
我还有几个问题。给定一个这样的类:
#nullable enable
class MyCollection<T> : IEnumerable<T>
{
Dictionary<int,T> _dict = new Dictionary<int,T>();
...
[MaybeNull]
public T this[int index]
{
get => this[index,default(T)];
set => _dict[index] = value;
}
// [MaybeNull,NotNullIfNotNull("defaultValue")] doesn't work properly
public T this[int index,[AllowNull] T defaultValue]
{
get {
if (_dict.TryGetValue(index,out T value))
return value;
return defaultValue;
}
}
// [returns IEnumerator<T> if T is struct,IEnumerator<T?> if T is class]
public IEnumerator<T> GetEnumerator() { ... }
...
}
void example()
{
MyCollection<string> a = new MyCollection<string>();
string x = a[45]; // Should warn (and it does)
a[45] = null; // Should warn (and it does)
string s1 = a[45,"-"]; // Should not warn
string s2 = a[45,null]; // Should warn (currently doesn't)
IEnumerator<string> e1 = a.GetEnumerator(); // Should warn (currently doesn't)
IEnumerator<string?> e2 = a.GetEnumerator(); // Should not warn
}
- 如何指定
this[int,T]
只能在defaultValue
为 null 或类型参数为T?
(例如T = string?
)时返回 null? - 如果
GetEnumerator()
是结构体,我如何指定IEnumerator<T>
返回T
,但如果IEnumerator<T?>
是类,我如何指定T
返回? - 如果有一个方法接受
Something<T>
参数,我怎么能表明这意味着Something<T>
当T
是一个结构体和Something<T?>
当 T 是一个类?
另请参阅:关于 nullability attributes 的 Microsoft 页面
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。