C # Generic class: suy ra kiểu không thể nullable từ tham số kiểu nullable
Nov 05 2020
Tôi sử dụng C # 8 kiểu tham chiếu nullable.
Tôi có một lớp chung có thể chấp nhận kiểu tham chiếu nullable làm tham số kiểu.
Có cách nào để khai báo kiểu không thể nullable dựa trên tham số kiểu chung có thể là kiểu tham chiếu nullable (hoặc thậm chí là cấu trúc Nullable) không?
abstract class Selector<T>
{
T SelectedItem;
// how to make item parameter not nullable?
abstract string Format(T! item);
// how to make item parameter not nullable?
Func<T!, string> FormatFunction;
}
Trả lời
4 YairHalberstadt Nov 05 2020 at 15:46
Sử dụng DisallowNullAttribute:
using System.Diagnostics.CodeAnalysis;
abstract class Selector<T>
{
T SelectedItem;
public abstract string Format([DisallowNull] T item);
}
var selector = default(Selector<string?>)!;
selector.Format(null); //warning CS8625: Cannot convert null literal to non-nullable reference type.