交错中的通用属性类型和可为空错误

问题描述 投票:0回答:1

非泛型接口不存在可为空标记的问题。 在下面的通用接口中,将 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; }
}
c# generics interface nullable
1个回答
0
投票

这里的问题是

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 中的可为空性和泛型了解更多信息。

© www.soinside.com 2019 - 2024. All rights reserved.