2013-04-23 50 views
2

因此,我試圖使用枚舉,可能以錯誤的方式,因爲我來自PHP。在C#中我有一個全球性的類,它的作用:瞭解枚舉 - 用作常量

public static class GlobalTypes 
{ 
    public enum assignmentType { SERV = "SERV", PROD = "PROD", PER = "PER", } 
} 

從那裏我試圖與實體交互做:

public static IEnumerable<Person> getAllAgents(int id) 
    { 
     using (var db = new LocAppContext()) 
     { 
      var person = (from p in db.Person 
          join la in db.LocationAssignment on p.id equals la.value 
          where la.locationID == id && la.type == GlobalTypes.assignmentType.PER 
          select p).ToList(); 

      return person; 
     } 

    } 

但我得到的錯誤:

Operator '==' cannot be applied to operands of type 'string' and 'LocApp.Helpers.Classes.LocationAssignments.GlobalTypes.assignmentType'

發生在

la.type == GlobalTypes.assignmentType.PER 

我的邏輯,這是從PHP的,是我想要一個全局常量,我可以調用任何地方「回聲」調用時,該常量的值,所以恆定值可以改變,但我不必改變它在一百萬個地方。

想法?

+1

只需溝'= 「SERV」'部分,它應該是好的去。下面是關於C#中枚舉用法的一些MSDN文檔:http://msdn.microsoft.com/en-ca/library/vstudio/cc138362.aspx編輯:另外,你的'la.type'應該被定義爲'GlobalTypes.assignmentType '不是一個字符串。 – 2013-04-23 20:20:48

+6

枚舉不是字符串,C#不是PHP。 – alex 2013-04-23 20:21:30

+0

@ChrisSinclair所以你說我可以這樣做:'&& GlobalTypes.assignmentType' ??它會知道我想要什麼? – TheWebs 2013-04-23 20:23:05

回答

4

如果你想要不變的字符串,那就不要使用枚舉。枚舉是用於整數類型。只需使用consts:

public static class MyClass 
{ 
    public const string PROD = "PROD"; 
    public const string DEV = "DEV"; 
} 

// elsewhere... 
la.type == MyClass.PROD; 
4

快速回答:

public enum assignmentType { SERV, PROD, PER } 

,並在比較中(假設la.type返回一個字符串):

where la.locationID == id && la.type == GlobalTypes.assignmentType.PER.ToString() 
+3

即使你不必使用枚舉,你爲什麼不想這麼做呢?使用枚舉聽起來像是解決這個問題的完美解決方案。 – Servy 2013-04-23 20:30:49

+0

問題:LINQ to Entities無法識別方法'System.String ToString()'方法,並且此方法無法轉換爲存儲表達式。 la.type,befor這是:la.type ==「PER」所以是它的一個字符串,錯誤仍然存​​在 – TheWebs 2013-04-23 20:34:43

+1

同意@Servy。枚舉是一個很好的解決方案,因爲它被用來對3個值進行分組。使用常量作爲別人建議刪除分組。也許使用ToString並保存到查詢中使用的臨時字符串。枚舉在代碼中的其他位置重用是有意義的。 – Dave 2013-04-23 20:37:16