繁体   English   中英

使用显式接口实现时,冲突约束'value'和'System.Enum'

[英]Conflicting constraints 'value' and 'System.Enum' when using explicit interface implementation

我正在构建一个可扩展的系统,用于在各种枚举类型之间进行转换。 这个想法是开发人员可以继承BaseEnumConverter类并为抽象方法Convert<TDestinationEnumType>提供实现。

然后,内部系统将调用此Convert方法。 要求是在某些验证逻辑之后将自动直接调用此方法的任何实现。

我通过使用接口,私有方法和显式接口实现来强制执行此规则:

public interface IEnumConverter
{
    TDestinationEnumType? Convert<TDestinationEnumType>(Enum sourceEnumValue) where TDestinationEnumType : struct, Enum;
}

public abstract class BaseEnumConverter : IEnumConverter
{
    public abstract TDestinationEnumType? Convert<TDestinationEnumType>(Enum sourceEnumValue)
        where TDestinationEnumType : struct, Enum;

    private TDestinationEnumType? ConvertWithValidation<TDestinationEnumType>(Enum sourceEnumValue)
        where TDestinationEnumType : struct, Enum
    {
        if (sourceEnumValue.GetType() == typeof(TDestinationEnumType))
        {
            return (TDestinationEnumType)sourceEnumValue;
        }
        return Convert<TDestinationEnumType>(sourceEnumValue);
    }

    TDestinationEnumType? IEnumConverter.Convert<TDestinationEnumType>(Enum sourceEnumValue)
    {
        return ConvertWithValidation<TDestinationEnumType>(sourceEnumValue);
    }
}

这样,对IEnumConverter引用的任何调用都将自动运行验证逻辑,然后运行转换逻辑。

问题

显式接口定义的签名具有以下编译错误:

Type parameter 'TDestinationEnumType' inherits conflicting constraints 'value' and 'System.Enum'

删除'struct'约束会删除编译错误,但是它会阻止我从Convert方法返回null结果,这也是此系统的要求。

所以我想知道的是:

  • 究竟是什么导致了这个错误?
  • 有没有解决方法? 不返回null不是我的选择。

在进一步调查中,这似乎与ReSharper有关。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM