枚举到类型的映射

时间:2020-01-29 07:02:25

标签: c# .net collections

我有一个看起来像:

的枚举
public enum FieldType
{

    Text,
    Image,
    ProgressBar,
    Group,
}

我想编写一个方法,该方法将返回用户必须为c#中的字段类型实例化的类的类型。

我想将创建对象的任务委托给我的Api用户。我知道每个枚举都映射到哪种类型。只是我无法返回某些常见或基本类型,因为它不会告诉用户他们必须创建哪种类型的对象。

例如,用户需要添加文本字段。所以我想返回必须实例化并传递所需属性的TextBox类型

如果我采用基类或接口,将无济于事。因为我需要公开类型而不是对象。

如果我使用“类型”类,那么他们必须使用反射并且仍然不知道他们必须传递哪些属性

我不知道这是解决问题的正确方法,还是应该考虑其他方法。我对这两种解决方案都开放。

之所以能更好地向用户公开类型,是因为用户会了解实例化中期望的属性。

或者,我可以编写基本属性接口,并且用户将传递属性名称和值,并使用反射设置该对象的属性。

interface IProperty<T>
{
  string propertyName {get;set;}

  T Value {get;set;}
}

但是我如何教育用户期望哪些属性。

2 个答案:

答案 0 :(得分:0)

我知道这是一种非常简单的方法,但是由于您仅使用枚举,因此我会保持简单,然后您可以在以后的代码中检查是否需要执行特定类型的实例东西。

class MyControlBuilder
{
    public Control Build(FieldType fieldType)
    {
        switch (fieldType)
        {
            case FieldType.Text:
                return new TextBox();
            case FieldType.Image:
                return new PictureBox();
            case FieldType.ProgressBar:
                return new ProgressBar();
            case FieldType.Group:
                return new GroupBox();
            default:
                throw new NotImplementedException();
        }
    }
}

使用方法示例:

        var builder = new MyControlBuilder();
        var control = builder.Build(FieldType.ProgressBar);
        if(control is ProgressBar progressBar)
        {
            progressBar.Minimum = 0;
            progressBar.Maximum = 100;
            progressBar.Value = 0;
        }

答案 1 :(得分:0)

当被问及关于映射时,Dictionary<K, V>是第一个想到的,例如

 private static Dictionary<FieldType, Type> s_ControlTypes = 
   new Dictionary<FieldType, Type>() {
     {FieldType.Text, typeof(TextBox)}, 
     {FieldType.Image, typeof(ImageBox)},
 };

 ...

 Control ctrl = Activator.CreateInstance(s_ControlTypes[FieldType.Text]) as Control;
 ...

或者(将控件创建的整个过程放入字典中)

 private static Dictionary<FieldType, Action<Control>> s_ControlCreators = 
   new Dictionary<FieldType, Action<Control>() {
     {FieldType.Text, () => {
        // You can well have an elaborated procedure  
        var result = new TextBox();

        result.Readonly := true;

        return result; 
      }}, 
     {FieldType.Image, () => new ImageBox()},
 };

 ...

 Control ctrl = s_ControlCreators[FieldType.Text]();
 ...

最后,您可以为扩展名enum实施扩展方法

 public static class FieldTypeExtensions {
   public static Control CreateControl(this FieldType value) {
     return s_ControlCreators[value]();  
   }
 }  

并拥有

 FieldType fieldType = FieldType.Text;

 ...

 Control ctrl = fieldType.CreateControl();