创建一个 returns 枚举底层 int 的委托,在运行时不知道枚举类型

Create a delegate which returns enum's underlying int, without knowing the enum type at runtime

我正在编写一个设置系统,它依赖于向属性添加属性,然后使用反射。

例如,我通过将 SliderAttribute 添加到浮动属性来创建滑块,然后找到所有这些属性并创建委托来修改关联的 属性,如下所示:

Func<float> getterDelegate = Delegate.CreateDelegate(typeof(Func<float>), arg, property.GetGetMethod()) as Func<float>;
Action<float> setterDelegate = Delegate.CreateDelegate(typeof(Action<float>), arg, property.GetSetMethod()) as Action<float>;

settingObj = new Slider(sliderAttribute, getterDelegate, setterDelegate);

现在,我想通过对枚举值应用相同的逻辑来创建多项选择对象。那就是我想生成 getter/setter 委托,这些委托通过基础类型(我们可以假设它始终是 int。)

修改枚举 属性

理想情况如下,returns 错误 ArgumentException: method return type is incompatible。如果我使用 'Enum' 类型,结果相同。

Func<int> getterDelegate = Delegate.CreateDelegate(typeof(Func<int>), arg, property.GetGetMethod()) as Func<int>;
Action<int> setterDelegate = Delegate.CreateDelegate(typeof(Action<int>), arg, property.GetSetMethod()) as Action<int>;

settingObj = new MultipleChoice(multipleChoiceAttribute, getterDelegate, setterDelegate, property.PropertyType);

您可以创建 return 的委托并采用实际的枚举类型,如下所示:

Delegate getterEnumDelegate = Delegate.CreateDelegate(
    typeof(Func<>).MakeGenericType(property.PropertyType), arg, property.GetGetMethod()
);
Delegate setterEnumDelegate = Delegate.CreateDelegate(
    typeof(Action<>).MakeGenericType(property.PropertyType), arg, property.GetSetMethod()
);

要将它们转换为 Action<int>Func<int>,您只需要做:

Func<int> getterDelegate = () => (int)getterEnumDelegate.DynamicInvoke();
Action<int> setterDelegate = x => setterEnumDelegate.DynamicInvoke(x);