gpt4 book ai didi

c# - 确定枚举类型

转载 作者:太空宇宙 更新时间:2023-11-03 18:37:12 24 4
gpt4 key购买 nike

我有两个枚举器和一个采用枚举器的方法。它们称为 ABC 和 DEF,方法称为 TestMethod(Enum myEnum)。代码如下:

public enum ABC
{
Zero,
One,
Two
};

public enum DEF
{
Zero,
One,
Two
};

public void TestEnum(Enum myEnum)
{
...
}

函数 TestEnum 采用任何枚举器。如何测试传入的参数属于两者中的哪一个?我可以盲目地开始用 try/catch cast 来测试它,但天哪,那太丑了。这样做有什么更清洁的方法吗?提前感谢您的帮助。

最佳答案

How can I test which one of the two does the passed in parameter belong to?

你可以调用 GetType:

Type type = myEnum.GetType();

请注意,您还不清楚之后要用它做什么。

或者:

if (myEnum is ABC)
{
}
else if (myEnum is DEF)
{
}

编辑:如果您能够更改方法签名并且如果您的调用者知道类型,那么根据 Jeppe 的评论,您可以使用:

public void TestEnum<T>(T value) where T : struct
{
// Use typeof(T) here
}

您不能将 T 限制为普通 C# 的枚举类型...尽管有 hacky ways通过后处理应用此类约束来编写代码。

关于c# - 确定枚举类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13592959/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com