c# - 如果枚举用作方法参数,是否始终需要在 C# 中进行强制转换?

标签 c# javascript casting enums

在方法调用中使用枚举作为参数时,是否必须将其转换为参数定义的类型?

最后两行代码显示了完全相同的方法调用,只不过其中一行被转换为 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/

相关文章:

swift - 如何在swift4中将字符转换为字符串?

c# - Linq to Entities 和复杂类型转换

python-3.x - python : casting map object to list makes map object empty?

c# - EF Core 中的数据库资源授权

c# - 模拟扩展方法导致 System.NotSupportedException

c# - 在 "Find all references"中显示方法名称 - C# Visual Studio

javascript - Node.js 使用 Series 函数(模式?)实现流控制的意外结果

php - 在 Jquery 中,如何提醒 JSON 对象的一部分?我得到 "undefined"

javascript - 可汗学院算法挑战 : Binary Search

c# - Linq to Entities Group By 那里有一些没有元素的组