从 Unity 配置传递枚举值

Passing Enum Value from Unity Configuration

我在从 Unity 传递枚举值时遇到问题。这是我的枚举

public enum MyChoice
    {
        Choice1 = 1,
        Choice2 = 2
    }

我已经为这个枚举类型注册了 typeAlias,如下所示。

<typeAlias alias ="MyChoice" type ="SomeNamespace.MyChoice, SomeAssembly" />

到目前为止一切顺利。现在,我需要将枚举值从配置文件传递给 class 的构造函数。我是这样做的:

<register type="IMyInterface" mapTo="SomeClass" name="MyClass">
      <constructor>
        <param name ="choice" value="MyChoice.Choice1"  />
      </constructor>
</register>

我收到错误消息 MyChoice.Choice1 不是 MyChoice 的有效值

有什么想法吗?

为了开箱即用,您应该使用枚举的实际值而不是名称。在这种情况下,您应该使用 "1".

而不是 "MyChoice.Choice1"

如果您想在配置中使用该名称(尽管发布的示例几乎总是使用枚举名称更有意义),那么您可以使用类型转换器。

这是一个示例配置:

<typeAlias alias ="EnumConverter" type ="SomeNamespace.EnumConverter`1, SomeAssembly" />

<register type="IMyInterface" mapTo="SomeClass" name="MyClass">
  <constructor>
    <param name ="choice" value="Choice1" typeConverter="EnumConverter[MyChoice]" />
  </constructor>
</register>

然后创建 EnumConverter:

public class EnumConverter<T> : System.ComponentModel.TypeConverter where T : struct
{
    public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
    {
        T result;

        if (value == null || !Enum.TryParse<T>(value.ToString(), out result))
        {
            throw new NotSupportedException();
        }

        return result;
    }
}