2013-12-16 14 views
9

Cơ sở dữ liệu tôi đang làm việc với hiện đang có một lĩnh vực varchar, và trong mã của tôi, tôi muốn để ánh xạ các giá trị tiềm năng cho một liệt kê như:Có thể đảm bảo giá trị của những gì ToString cho một enum sẽ được?

public enum UserStatus 
{ 
    Anonymous, 
    Enrolled, 
    SuperUser 
} 

Ở cấp cơ sở dữ liệu cho cột này, có một Constrain trên nó hợp giá trị phải là:

ANONYMOUS 
ENROLLED 
SUPERUSER 

có thể cho tôi để làm:

UserStatus.SuperUser.ToString() 

và có mà giá trị được superuser, và điều này được bao gồm kiến và không vít xuống đường?

+1

Nếu bạn kiểm soát được bộ mã, thì chắc chắn bạn có thể đảm bảo điều đó. –

+1

['ToUpperInvariant()'] (http://msdn.microsoft.com/en-us/library/system.string.toupperinvariant (v = vs.110) .aspx)? – PoByBolek

+1

Bạn thậm chí có thể không cần điều này. Bạn không chỉ định phương ngữ SQL của bạn, nhưng nhiều trong số chúng không phân biệt dạng chữ theo mặc định cho văn bản, có nghĩa là 'SuperUser'' sẽ thỏa mãn ràng buộc. – hvd

Trả lời

6

Bạn không có thể ghi đè ToString cho enums, thay vào đó bạn có thể tạo riêng của bạn Extension Method như:

public static class MyExtensions 
{ 
    public static string ToUpperString(this UserStatus userStatus) 
    { 
     return userStatus.ToString().ToUpper();// OR .ToUpperInvariant 
    } 
} 

Và sau đó gọi nó thích:

string str = UserStatus.Anonymous.ToUpperString(); 
+0

ToUpperInvariant() có hoạt động không? – loyalflow

+0

@ user1361315, nó dành cho việc chuyển đổi văn hóa không nhạy cảm với chữ hoa. xem [this] (http://msdn.microsoft.com/en-us/library/system.string.toupperinvariant (v = vs.110) .aspx) – Habib

+0

Tôi không quan tâm đến văn hóa, nó chỉ dành cho cơ sở dữ liệu nên không nên thay đổi theo văn hóa. Vì vậy, sử dụng ToUpperInvariant sau đó? – loyalflow

7

Một giải pháp tốt hơn có thể tận dụng lợi thế của số DescriptionAttribute:

public enum UserStatus 
{ 
    [Description("ANONYMOUS")] 
    Anonymous, 
    [Description("ENROLLED")] 
    Enrolled, 
    [Description("SUPERUSER")] 
    SuperUser 
} 

Sau đó sử dụng một cái gì đó như:

/// <summary> 
/// Class EnumExtenions 
/// </summary> 
public static class EnumExtenions 
{ 
    /// <summary> 
    /// Gets the description. 
    /// </summary> 
    /// <param name="e">The e.</param> 
    /// <returns>String.</returns> 
    public static String GetDescription(this Enum e) 
    { 
     String enumAsString = e.ToString(); 
     Type type = e.GetType(); 
     MemberInfo[] members = type.GetMember(enumAsString); 
     if (members != null && members.Length > 0) 
     { 
      Object[] attributes = members[0].GetCustomAttributes(typeof(DescriptionAttribute), false); 
      if (attributes != null && attributes.Length > 0) 
      { 
       enumAsString = ((DescriptionAttribute)attributes[0]).Description; 
      } 
     } 
     return enumAsString; 
    } 

    /// <summary> 
    /// Gets an enum from its description. 
    /// </summary> 
    /// <typeparam name="TEnum">The type of the T enum.</typeparam> 
    /// <param name="description">The description.</param> 
    /// <returns>Matching enum value.</returns> 
    /// <exception cref="System.InvalidOperationException"></exception> 
    public static TEnum GetFromDescription<TEnum>(String description) 
     where TEnum : struct, IConvertible // http://stackoverflow.com/a/79903/298053 
    { 
     if (!typeof(TEnum).IsEnum) 
     { 
      throw new InvalidOperationException(); 
     } 
     foreach (FieldInfo field in typeof(TEnum).GetFields()) 
     { 
      DescriptionAttribute attribute = Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute)) as DescriptionAttribute; 
      if (attribute != null) 
      { 
       if (attribute.Description == description) 
       { 
        return (TEnum)field.GetValue(null); 
       } 
      } 
      else 
      { 
       if (field.Name == description) 
       { 
        return (TEnum)field.GetValue(null); 
       } 
      } 
     } 
     return default(TEnum); 
    } 
} 

Vì vậy, bây giờ bạn đang tham khảo UserStatus.Anonymous.GetDescription().

Tất nhiên bạn luôn có thể tự tạo DatabaseMapAttribute của riêng mình (hoặc những gì bạn có) và tạo các phương pháp mở rộng của riêng bạn. Sau đó, bạn có thể hủy tham chiếu đến System.ComponentModel. Hoàn toàn là cuộc gọi của bạn.

+0

Nếu bạn định nghĩa nó là 'GetDescription()', bạn cũng phải gọi nó là 'GetDescription()', không phải là 'ToDescription()' :) – hvd

+0

@hvd: Cuộc gọi tốt. Vẫn nhận được thông qua một thứ hai. ;-) –

+2

Điều này thực sự tốt hơn? Đánh giá từ số lượng mã bạn phải duy trì tôi muốn giải pháp của Habib ... – PoByBolek

1

Enum.ToString hỗ trợ 4 different formats. Tôi muốn đi cho:

UserStatus.SuperUser.ToString("G").ToUpper(); 

"G" đảm bảo rằng nó sẽ cố gắng đầu tiên để có được đại diện chuỗi của enum của bạn.

Các vấn đề liên quan