作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
考虑以下人为的类:
public sealed class Test<T>
{
public void SetItem(T item)
{
_item = item;
}
public T GetItem()
{
return _item;
}
T _item; // warning CS8618: Non-nullable field '_item' is uninitialized.
} // Consider declaring the field as nullable.
var test1 = new Test<int>();
test1.SetItem(1);
Console.WriteLine(test1.GetItem());
var test2 = new Test<string>();
test2.SetItem("One");
Console.WriteLine(test2.GetItem());
nullable
编译时启用。
warning CS8618: Non-nullable field '_item' is uninitialized. Consider declaring the field as nullable.
T? _item; // Error: A nullable type parameter must be known to be a value type or non-nullable reference type
public sealed class Test<T> where T: struct
var test2 = new Test<string>();
不会编译
public sealed class Test<T> where T: class
...
T? _item;
var test1 = new Test<int>();
不会编译。
public sealed class Test<T>
{
public void SetItem(T item)
{
_item = item;
}
public T GetItem()
{
return _item;
}
#pragma warning disable CS8618 // Non-nullable field is uninitialized. Consider declaring as nullable.
T _item;
#pragma warning restore CS8618 // Non-nullable field is uninitialized. Consider declaring as nullable.
}
where T : struct
,这 - 如上所述 - 不能解决问题。
public sealed class Test<T>
{
public void SetItem([CanBeNull] T item)
{
_item = item;
}
[CanBeNull] public T GetItem()
{
return _item;
}
[CanBeNull] T _item = default!;
}
var test = new Test<string>();
Console.WriteLine(test.GetItem().Length); // Warning: Possible null reference exception.
test.GetItem()
可能返回空值 - 即使编译器没有。
public sealed class Test<T>
{
public void SetItem(T item)
{
_item = item;
}
public T GetItem()
{
return _item;
}
T _item = default!;
}
var test = new Test<string?>();
var test = new Test<string?>(); // Note "string?"
Console.WriteLine(test.GetItem().Length); // Warning about test.GetItem() possibly null.
_item
除非明确设置,否则将被访问,因此更像是这样:
public sealed class Test<T>
{
public void SetItem(T item)
{
_wasSet = true;
_item = item;
}
public T GetItem()
{
if (!_wasSet)
throw new InvalidOperationException("No item set.");
return _item;
}
T _item = default!;
bool _wasSet;
}
_item
实际上是用于队列前端的单独值,其中队列的其余部分存储在
Queue<T>
中。这不是我做的方式,真的,但这就是我正在使用的......)
最佳答案
作为一种可能的选择,您可以使用 default
的组合文字和 null-forgiving
运营商,比如
private T _item = default!;
关于c# - 避免对具有可为空类型/字段的泛型发出警告的最佳方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59212963/
我是一名优秀的程序员,十分优秀!