簡體   English   中英

通用方法並將任何枚舉作為參數傳遞

[英]Generic method and passing any enum as parameter

所有,

我正在嘗試整理枚舉框架中的最后幾位。

我的目標:我想發送任何枚舉類型並將其轉換為List並將其綁定到下拉列表。 我將使用ObjectDataSource作為給定下拉列表的DataSource。 我想創建一個僅包含一個參數的復合控件; 枚舉類型。 復合控件將整理數據綁定以及所有其他位和結尾。

現在,我唯一的問題是將通用方法轉換為與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。

這應該對您有幫助。 (如果T不是枚舉類型,則將引發Exception。)

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
}

替代了Magnus,但是這個想法幾乎是完全一樣的(只是不想在被擊敗之后將它扔掉;-))-只是遍歷枚舉值而不是int。 用法相同:

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
        }
    }
}

我似乎對這個問題的處理有些不同,並提出了一些簡潔的方法,似乎對我有用。 我不能聲稱這是原始作品,因為我不記得自己是否找到並復制了它,或者是否將我發現的點點滴滴與自己的一些原始作品放在一起。 我在枚舉上添加了一個擴展方法,該方法為我提供了一個ToDisplayText函數,用於獲取同名的自定義枚舉屬性。

    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
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM