Доберитесь Перечисление <T> оценивают Описание

Это может быть глупый вопрос, но почему бы вам не отсканировать & amp; сохранить непосредственно в бинарный или .ply файл? Или даже сканирование & amp; сохранить в сетку или в какую-нибудь вокселизированную сетку

Вы также можете посмотреть подход, использованный в этом проекте, особенно PlyImporter.cs

5
задан Mitch Wheat 18 November 2008 в 10:02
поделиться

3 ответа

Необходимо измениться:

public static string Description(Enum value)
{
  ...
}

кому:

public static string Description(T value)
{
   ...
}

таким образом, это принимает значение перечисления. Теперь вот то, где это становится хитрым: у Вас есть значение, но атрибуты украшают поле, которое содержит значение.

На самом деле необходимо отразиться по полям перечисления и проверить значение каждого против значения, которое Вам дали (результаты должны кэшироваться для производительности):

foreach(var field in typeof(T).GetFields())
{
    T fieldValue;

    try
    {
        fieldValue = (T) field.GetRawConstantValue();
    }
    catch(InvalidOperationException)
    {
        // For some reason, one of the fields returned is {Int32 value__},
        // which throws an InvalidOperationException if you try and retrieve
        // its constant value.
        //
        // I am unsure how to check for this state before
        // attempting GetRawConstantValue().

        continue;
    }

    if(fieldValue == value)
    {
        var attribute = LMIGHelper.GetAttribute(field, typeof(DescriptionAttribute)) as DescriptionAttribute;

        return attribute == null ? value.ToString() : attribute.Description;
    }
}

Редактирование, рассматривающее последующий вопрос

FillComboFromEnum метод пропускает параметр типа для перечисления. Попробуйте это:

public static void FillComboFromEnum<T>(ComboBox Cbo, BindingList<KeyValuePair<T, string>> List) where T : struct

Заметьте, что я вынудил тип быть структурой. Это не полное ограничение перечисления, но это не ближе, чем ничто.

2
ответ дан 14 December 2019 в 19:29
поделиться

Смотрите на эту статью. Можно сделать это использование Системы. ComponentModel. DescriptionAttribute или создание Вашего собственного атрибута:

/// <summary>
/// Provides a description for an enumerated type.
/// </summary>
[AttributeUsage(AttributeTargets.Enum | AttributeTargets.Field, 
 AllowMultiple = false)]
public sealed class EnumDescriptionAttribute :  Attribute
{
   private string description;

   /// <summary>
   /// Gets the description stored in this attribute.
   /// </summary>
   /// <value>The description stored in the attribute.</value>
   public string Description
   {
      get
      {
         return this.description;
      }
   }

   /// <summary>
   /// Initializes a new instance of the
   /// <see cref="EnumDescriptionAttribute"/> class.
   /// </summary>
   /// <param name="description">The description to store in this attribute.
   /// </param>
   public EnumDescriptionAttribute(string description)
       : base()
   {
       this.description = description;
   }
} 

Затем необходимо украсить перечислимые значения этим новым атрибутом:

public enum SimpleEnum
{
   [EnumDescription("Today")]
   Today,

   [EnumDescription("Last 7 days")]
   Last7,

   [EnumDescription("Last 14 days")]
   Last14,

   [EnumDescription("Last 30 days")]
   Last30,

   [EnumDescription("All")]
   All
} 

Все "волшебство" происходит в следующих дополнительных методах:

/// <summary>
/// Provides a static utility object of methods and properties to interact
/// with enumerated types.
/// </summary>
public static class EnumHelper
{
   /// <summary>
   /// Gets the <see cref="DescriptionAttribute" /> of an <see cref="Enum" /> 
   /// type value.
   /// </summary>
   /// <param name="value">The <see cref="Enum" /> type value.</param>
   /// <returns>A string containing the text of the
   /// <see cref="DescriptionAttribute"/>.</returns>
   public static string GetDescription(this Enum value)
   {
      if (value == null)
      {
         throw new ArgumentNullException("value");
      }

      string description = value.ToString();
      FieldInfo fieldInfo = value.GetType().GetField(description);
      EnumDescriptionAttribute[] attributes =
         (EnumDescriptionAttribute[])
       fieldInfo.GetCustomAttributes(typeof(EnumDescriptionAttribute), false);

      if (attributes != null && attributes.Length > 0)
      {
         description = attributes[0].Description;
      }
      return description;
   }

   /// <summary>
   /// Converts the <see cref="Enum" /> type to an <see cref="IList" /> 
   /// compatible object.
   /// </summary>
   /// <param name="type">The <see cref="Enum"/> type.</param>
   /// <returns>An <see cref="IList"/> containing the enumerated
   /// type value and description.</returns>
   public static IList ToList(this Type type)
   {
      if (type == null)
      {
         throw new ArgumentNullException("type");
      }

      ArrayList list = new ArrayList();
      Array enumValues = Enum.GetValues(type);

      foreach (Enum value in enumValues)
      {
         list.Add(new KeyValuePair<Enum, string>(value, GetDescription(value)));
      }

      return list;
   }
} 

Наконец, можно затем просто связать поле комбинированного списка:

combo.DataSource = typeof(SimpleEnum).ToList();
5
ответ дан 14 December 2019 в 19:29
поделиться

Перечисление не имеет Описания () методом. Лучшее, которое Вы могли сделать, имеют Вашу реализацию перечисления интерфейс, который имеет Описание () метод. Если Вы делаете это, то Вы можете иметь

public static BindingList<KeyValuePair<T extends _interface_, String>> getBindingList()

и затем, в котором можно обратиться к

T foo = ...?
foo.Description(...);
-2
ответ дан 14 December 2019 в 19:29
поделиться
Другие вопросы по тегам:

Похожие вопросы: