[英]Accept more than one type of enum in functions
I currently have two enums : 我目前有两个枚举:
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
}
and I'm using one of the enum in another class : 我正在另一类中使用一个枚举:
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
}
}
but now I want to make that Dictionary
and that function more generic to make it accept the two different types of enum but I still don't want it to accept more than these two types, is there a way to do that easily ? 但是现在我想使Dictionary
和该函数更通用,以使其接受两种不同类型的枚举,但是我仍然不希望它接受比这两种类型更多的枚举,有没有办法轻松地做到这一点?
C# 7.3 includes an Enum
contraint that you can use to enforce the type to be any enumeration type: 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
}
}
There is no support in the language for specifying specific types of enums though, at least not at compile time. 虽然至少在编译时没有指定语言的特定类型的枚举,但该语言没有支持。 You can always check the type at runtime: 您始终可以在运行时检查类型:
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
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.