在方法调用中使用枚举作为参数时,是否必须将其转换为参数定义类型?
最后两行代码显示完全相同的方法调用,除了一个被强制转换为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);
}}
*这是过于简化的代码,但概念仍然存在。除了你在这里看到的使用枚举的原因之外还有很多原因。
答案 0 :(得分:1)
在方法调用中使用枚举作为参数时,是否必须将其转换为参数定义类型?
来自this page:
但是,从枚举类型转换为整数类型需要显式强制转换。例如,以下语句通过使用强制转换从枚举转换为int,将枚举器Sun分配给int类型的变量。
int x = (int)Days.Sun;