c# - 在函数中接受一种以上类型的枚举
问题描述
我目前有两个枚举:
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# 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
}
推荐阅读
- tsql - T-sql 中的 Datediff 函数
- excel - 在 ActiveX 文本框中分隔 1000
- javascript - 使用 pupeteer 拦截和模拟 WebSocket 请求/响应
- wordpress - 对齐面板底部的按钮
- javascript - 如何在webview中使用在BrowserWindow中获得的cookie
- java - Java 原始长溢出
- ios - 自动调整嵌入在 UITableView 中的 UICollectionView 单元格不起作用
- javascript - 从内部组件触发 Material TextField onChange
- python - 将包含 JSON 列表的 Pandas 列转换为新列
- php - 通过 Facebook Marketing API 创建广告时出错