2014-02-18 67 views
-2

如何通过使用enum成员来调用期望int值的方法。我不想让被调用的方法必须知道枚举。将enum成员传递给方法

public enum Volume : int 
{ 
    Low = 1, 
    Medium = 2, 
    High = 3 
} 

public void Start() { 
    DoSomeWork(Volume.Low); //this complains 
    //this works DoSomething((int)Volume.Low); 

} 

public void DoSomeWork(int vol) { 
    //Do something 
} 
+4

你自己在问题中有答案。为什么要问这个问题?说了这样的话,你会更好的方法接受枚举。让它接受一个魔法int将会使那个需要记住int意味着什么的调用者非常困惑。 – Servy

回答

3

投它明确地int(因为你已经想通了):

DoSomeWork((int)Volume.Low) 

从枚举的基础类型隐式转换是被禁止的,因为有很多的情况下,当这种转换不合理。 @EricLippert对此足以解释得很好here

但是,如果你不使用它,为什么要引入枚举?如果程序中的体积速率由枚举指定 - 那么这是您的方法应该预期的参数类型。

+0

是的,但id不是。编译器不知道Volume.Low的类型是int,特别是因为我设置了枚举的基类型? – bitshift

+0

@bitshift,请参阅更新和一些解释 – Andrei

+0

好吧,现在我查了一下,enum成员和一个int可能是相同的intregal类型,他们需要明确的转换从一个到另一个。 http://csharp-station.com/Tutorial/CSharp/Lesson17 – bitshift

1

这样称呼它:

DoSomeWork((int) Volume.Low); 
0

为什么不采用这种方式:

public void DoSomeWork(Volume volume) { 
    //Do something 
} 
0

如文档指出

Every enumeration type has an underlying type, which can be any integral type except char. The default underlying type of the enumeration elements is int.

所以你可以简单的将它转换成int并将其传递给该方法。

DoSomeWork((int)Volume.Low);