在方法调用中使用枚举作为参数时,是否必须将其转换为参数定义的类型?
最后两行代码显示了完全相同的方法调用,只不过其中一行被转换为 int,另一行则不是。这两行的结果应该是什么?
请注意,在我的示例中,包含枚举的文件是 .cs 文件,另一个(此处写得不好)是 aspx.cs 文件。我认为这根本不重要,但也许确实重要。
谢谢!
**fileOne.cs**
[Imported]
public class Foo
{
[Imported]
public class Bar
{
[Imported]
[PreserveCase]
public enum Bam
{
[PreserveCase]
Low = 10,
[PreserveCase]
Medium = 50,
[PreserveCase]
High = 100
}
}
…code…
[PreserveCase]
public static void someMethod(string aString, int aNumber) {}
…code…
}
**fileTwo.aspx.cs**
…code…
string someStuffForJscript = @”
function afunction(doesntMatter)
{{
Foo.Bar.someMethod(""This is a string."", (int)Foo.Bar.Bam.Medium);
Foo.Bar.someMethod(""This is a string."", Foo.Bar.Bam.Medium);
}}
*这是过于简化的代码,但概念仍然存在。除了您在这里看到的之外,关于使用枚举的原因还有很多。
最佳答案
When using an enum as a parameter in a method call, must I cast it to the parameters defined type?
来自this page :
但是,要从枚举类型转换为整型类型,需要显式强制转换。例如,以下语句通过使用强制转换将 enum 转换为 int,将枚举数 Sun 分配给 int 类型的变量。
int x = (int)Days.Sun;
关于c# - 如果枚举用作方法参数,是否始终需要在 C# 中进行强制转换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23073347/