非泛型接口不存在可为空标记的问题。 在下面的通用接口中,将 TKey 标记为可为空会生成编译器错误。 为什么 ?是否可以将泛型属性类型标记为可为空?
错误CS0738“TClass”未实现接口成员 'ITest.Info1'。 “TClass.Info1”无法实现“ITest.Info1” 因为它没有匹配的返回类型“int”。
public interface ITest<TKey>
{
public TKey? Info1 { get; set; }
public BHPGuard.Domain.LocationType.LocationType? Type { get; set; }
}
public class TClass : ITest<int>
{
public int? Info1 { get; set; }
public LocationType.LocationType? Type { get; set; }
// int ITest<int>.Info1 { get; set; }
}
这里的问题是
TKey
是不受约束的泛型类型,因此对于值类型 TKey?
是 TKey
。接口的实现是:
public class TClass : ITest<int>
{
public int Info1 { get; set; }
public LocationType? Type { get; set; }
}
或
public class TClass : ITest<int?>
{
public int? Info1 { get; set; }
public LocationType? Type { get; set; }
}
请参阅 .NET 6 中的可为空性和泛型了解更多信息。