2012-07-26 48 views
1

Visual Studio中報告說 「‘PhoenixEngineTypes.BehaviorTypes’是‘類型’,但使用類似‘變量’」。如何在C#4.0中使用類型作爲函數參數?

public void AddBehavior(BehaviorTypes type) 
    { 
     if (Enum.IsDefined(BehaviorTypes, type)) 
     { 
     switch (type) 
     { 
      case BehaviorTypes.render: 
      break; 
     } 
    } 

BehaviorTypes的定義是:

[Flags] 
enum BehaviorTypes : uint 
{ 
    default_behavior = 1 >> 0, 
    select = 1 >> 1, 
    render = 1 >> 2, 
    animate = 1 >> 3, 
    navigate = 1 >> 4, 
    rotate = 1 >> 5, 
    group = 1 >> 6, 
    scale = 1 >> 7, 
    collide = 1 >> 8, 
    kill = 1 >> 9, 
    attack = 1 >> 10, 
    audio = 1 >> 11, 
    all = UInt32.MaxValue 
} 

最後:

public static bool IsDefined(Type enumType, object value); 

我爲什麼能做到這一點呢? 我試過用typeof(type)它編譯,但爲什麼浪費一個函數調用時,類型不變?我不應該直接使用令牌嗎?

回答

1

你需要調用IsDefined如下

Enum.IsDefined(typeof(BehaviorTypes), type) 

,因爲它預計Type輸入一個實例。 BehaviorTypes不是Type的實例,但您可以通過使用typeof得到相應的Type實例的類型。

http://msdn.microsoft.com/en-us/library/system.enum.isdefined.aspx

+0

那麼,爲什麼VS錯誤說BehaviorTypes是一種類型,但使用像變量?混亂。 – 2012-07-26 22:40:51

+0

'行爲類型'是一種類型。這是一個枚舉。該方法需要引用Type類的一個實例,或者是一個變量(如果您願意的話(有關一般類型和類Type的說法,有點混淆)。你可以做'var t = typeof(BehaviorTypes)'並傳遞't',如果這樣做更清楚的話。 – 2012-07-26 22:48:21

+0

我看到類型和類型。衛生署! – 2012-07-26 22:55:54

相關問題