首页 > 解决方案 > 在函数中接受一种以上类型的枚举

问题描述

我目前有两个枚举:

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
    }
}

但现在我想让它Dictionary和那个函数更通用,让它接受两种不同类型的枚举,但我仍然不希望它接受超过这两种类型,有没有办法轻松做到这一点?

标签: c#enumsuwp

解决方案


C# 7.3 包含一个Enum约束,可用于将类型强制为任何枚举类型:

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
}

推荐阅读