【问题标题】:Accept more than one type of enum in functions在函数中接受一种以上类型的枚举
【发布时间】:2019-10-05 04:24:07
【问题描述】:

我目前有两个枚举:

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 和该函数更通用,以使其接受两种不同类型的枚举,但我仍然不希望它接受超过这两种类型,有没有办法这么容易?

【问题讨论】:

  • 因为 2 个枚举共享相同的底层值,您应该创建 2 个单独的字典,1 个用于 PosteComponent,1 个用于 LigneComponent。其他组合策略无法区分 LIEN 与 BT 等值
  • 好吧,那是个坏消息
  • 只用一个替换这两个枚举有意义吗?
  • 不是那种情况,我在两个不同的类中使用这些枚举,它们专注于我的应用程序的两个不同部分

标签: c# enums uwp


【解决方案1】:

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
}

【讨论】:

  • 您的解决方案是一个非常好的解决方法,它非常适合我想做的事情,非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-21
  • 1970-01-01
  • 2021-06-11
相关资源
最近更新 更多