2012-01-29 5 views
0

모든 임의의 열거를 전달일반적인 방법 및 매개 변수

은 내가 열거 프레임 워크 내 마지막 비트를 분류하는 것을 시도하고있다.

내 목표 : 임의의 열거 형을 보내고 목록으로 변환하여 드롭 다운 목록에 바인딩하고 싶습니다. 주어진 드롭 다운 목록에 대해 DataSource로 ObjectDataSource를 사용합니다. 하나의 매개 변수 만 사용하는 복합 컨트롤을 만들고 싶습니다. enum 유형. 복합 컨트롤은 데이터 바인딩과 다른 모든 비트와 b을 분류합니다.

이제는 일반적인 방법을 ObjectDataSource와 호환되도록 변환하는 것이 유일한 문제입니다.

다음은 현재 ObjectDataSource에서 사용해야하는 현재 메서드 코드입니다. 따라서이 메서드는 정상적으로 작동하고 Enum 형식의 WeekDays에 대한 항목 목록을 반환합니다. 그러나 동일한 기능이 필요하지만 WeekDays를 모든 유형의 열거 형으로 대체해야합니다.

코드 :

public class DropDownData 
{ 

    public EnumDataItemList GetList() 
    { 
     EnumDataItemList items = new EnumDataItemList(); 

     foreach (int value in Enum.GetValues(WeekDays)) 
     { 
      EnumDataItem item = new EnumDataItem(); 

      WeekDays d = (WeekDays)value; 

      //Set display text 
      if (!string.IsNullOrEmpty(DataHandlers.GetAttributeValue<DisplayTextAttribute, string>(d))) 
      { 
       //Translation logic goes here 
       item.Text = DataHandlers.GetAttributeValue<DisplayTextAttribute, string>(d); 
      } 
      else 
      { 
       //Translation logic goes here 
       item.Text = Enum.GetName(typeof(WeekDays), value); 
      } 

      item.Value = value; //Actual value 
      item.ToolTip = DataHandlers.GetAttributeValue<ToolTipAttribute, string>(d); 
      item.Description = DataHandlers.GetAttributeValue<Lia.Library.Enums.CustomAttributes.DescriptionAttribute, string>(d); 
      item.HelpText = DataHandlers.GetAttributeValue<HelpTextAttribute, string>(d); 
      item.ExcludeOnBinding = DataHandlers.GetAttributeValue<ExcludeOnBinding, bool>(d); 

      if (!item.ExcludeOnBinding) 
      { 
       items.Add(item);      
      } 
     } 
     return items; 
    } 

} 

public class EnumDataItemList : List<EnumDataItem> 
{ 

} 

는 지금까지 내가 아는 한, 내가 ObjectDataSource를 함께 일반적인 방법을 사용할 수 있지만, 일반 클래스 괜찮습니다. 난 그냥 일반적인 클래스와 모든 도움을 많이 받아 주셔서 작동하도록 얻을 수 없습니다. 모두 작동하면 완벽한 솔루션을 공유하게되어 기쁩니다.

Framework 2.0을 사용하고 있습니다.

답변

3

도움이 될 것입니다. (T는 열거 형이 아닌 경우 예외가 발생합니다.)

public static EnumDataItemList GetList<T>() where T : struct 
{ 
    EnumDataItemList items = new EnumDataItemList(); 
    foreach (int e in Enum.GetValues(typeof(T))) 
    { 
     EnumDataItem item = new EnumDataItem(); 
     item.Text = Enum.GetName(typeof(T), e); 
     item.Value = e; 
    } 
    //Rest of code goes here 
} 

사용법 :

: 당신은 일반적인 방법을 사용하지 않으려면

EnumDataItemList days = GetList<WeekDays>(); 

, 당신이 그것을 변경할 수 있습니다

public static EnumDataItemList GetList(Type t) 
{ 
     EnumDataItemList items = new EnumDataItemList(); 
     foreach (int e in Enum.GetValues(t)) 
     { 
      EnumDataItem item = new EnumDataItem(); 
      item.Text = Enum.GetName(t, e); 
      item.Value = e; 
     } 
     //Rest of code goes here 
} 
2

Magnus '의 대안이지만 아이디어는 거의 똑같습니다. 단지 int가 아닌 enum 값을 반복합니다. 같은 사용 :

public static class DropDownData 
{ 
    // struct, IComparable, IFormattable, IConvertible is as close as we'll 
    // get to an Enum constraint. We don't actually use the constraint for 
    // anything except rudimentary compile-time type checking, though, so 
    // you may leave them out. 
    public static EnumDataItemList GetList<T>() 
      where T : struct, IComparable, IFormattable, IConvertible 
    { 
     // Just to make the intent explicit. Enum.GetValues will do the 
     // type check, if this is left out: 
     if (!typeof(T).IsEnum) 
     { 
      throw new ArgumentException("Type must be an enumeration"); 
     } 

     EnumDataItemList items = new EnumDataItemList(); 

     foreach (Enum e in Enum.GetValues(typeof(T))) 
     { 
      EnumDataItem items = new EnumDataItem(); 

      // Note: This assumes the enum's underlying type is 
      // assignable to Int32 (for example, not a long): 
      int value = Convert.ToInt32(e); 

      // The same attribute retrieval code as in the 
      // WeekDays example, including: 
      item.Text = e.ToString(); // e is Enum here, no need for GetName 
     } 
    } 
} 
0

내가 보인다는 조금 다르게이 문제에 사라 나를 위해 일을 표시 상당히 간결 뭔가 해낸 것으로. 나는 그것을 발견하고 그것을 복사했는지, 또는 내가 찾은 조각과 조각들을 모아서, 내 자신의 독창적 인 작품으로 기억한다면, 이것을 원래의 저작으로 주장 할 수는 없다. 동일한 이름의 사용자 정의 enum 속성을 가져 오는 ToDisplayText 함수를 제공하는 enum에 확장 메서드를 추가했습니다.

this.ddlBlah.DataSource = 
     Enum.GetValues(typeof(MyEnum)).Cast<MyEnum>() 
     .ToDictionary(x => x, x => x.ToDisplayText()); 
    this.ddlBlahs.DataValueField = "key"; 
    this.ddlBlah.DataTextField = "value"; 
    this.ddlBlah.DataBind(); 


public static string ToDisplayText(this Enum Value) 
{ 
    try 
    { 
    Type type = Value.GetType(); 
    MemberInfo[] memInfo = type.GetMember(Value.ToString()); 

    if (memInfo != null && memInfo.Length > 0) 
    { 
     object[] attrs = memInfo[0].GetCustomAttributes(
            typeof(DisplayText), 
            false); 
     if (attrs != null && attrs.Length > 0) 
     return ((DisplayText)attrs[0]).DisplayedText; 
    } 
    } 
    catch (Exception ex) 
    { 
    throw new Exception("Your favorite error handling here"); 
    } 
    return Value.ToString(); 

    // End of ToDisplayText() 
} 


[System.AttributeUsage(System.AttributeTargets.Field)] 
public class DisplayText : System.Attribute 
{ 
    public string DisplayedText; 

    public DisplayText(string displayText) 
    { 
    DisplayedText = displayText; 
    } 

    // End of DisplayText class definition 
}