簡體   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