接受多种类型的函数枚举

时间:2019-07-16 11:58:16

标签: c# enums uwp

我目前有两个枚举:

public enum LigneComponent
{
    LIEN = 0,
    SUPPORT = 1,
    OUVRAGE = 2,
}



public enum PosteComponent
{
    BT = 0,
    COMPTEUR = 1,
    AMM = 2,
    TFM = 3,
    HTA = 4,
    DLD = 5,
    GENERALITES = 6
}

并且我正在另一个类中使用一个枚举:

public class ExcelReader
{
    internal Dictionary<InfosPosteViewModel.PosteComponent, StorageFile> ExcelDataFiles { get; set; }

    internal async Task SetupExcelFiles(Dictionary<InfosPosteViewModel.PosteComponent, string> fileKeyNames, StorageFolder filesDirectory)
    {
        //code sample here
    }
}

但是现在我想使Dictionnary和该函数更通用,以使其接受两种不同类型的枚举,但是我仍然不希望它接受这两种以上的枚举,有没有办法轻松做到这一点?

1 个答案:

答案 0 :(得分:2)

C#7.3包含一个Enum约束,您可以使用它来强制类型为 any 枚举类型:

public class ExcelReader<T> where T : Enum
{
    internal Dictionary<T, StorageFile> ExcelDataFiles { get; set; }

    internal async Task SetupExcelFiles(Dictionary<T, string> fileKeyNames, StorageFolder filesDirectory)
    {
        //code sample here
    }
}

尽管至少在编译时没有指定语言的特定类型的枚举。您始终可以在运行时检查类型:

internal async Task SetupExcelFiles(Dictionary<T, string> fileKeyNames, StorageFolder filesDirectory)
{
    if (typeof(T) != typeof(LigneComponent) && typeof(T) != typeof(PosteComponent))
        throw new InvalidOperationException("Invalid type argument");

    //code sample here
}