如何避免在MVC CustomModelBinding中使用魔术字符串?

时间:2019-02-03 20:08:28

标签: c# model-view-controller reflection model-binding

我有一种方法,可以根据属性值确定要实例化的抽象类型的具体类型:

Text-1Text-2Text-3

如何(可能使用反射)如何确定属性private static Type GetModelType(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType) { if (modelType != typeof(MyAbstractClass)) return modelType; var key = "MyAbstractClass.ConcreteTypeEnum"; if (bindingContext.ValueProvider.ContainsPrefix(key)) { var concreteTypeName = bindingContext.ValueProvider.GetValue(key).AttemptedValue; modelType = Type.GetType( $"{modelType.Namespace}.{concreteTypeName}, {modelType.Assembly}" ); } } return modelType; } 的名称而不使用字符串来查找?如果有人重命名了属性,我不想破坏我的模型绑定。

我在考虑

"MyAbstractClass.ConcreteTypeEnum"

...但是没有这种生物。

1 个答案:

答案 0 :(得分:2)

您可以使用Minimum value from ['-0.0069', '-0.0201', '0.0194', '-0.0000'] is -0.0000 Minimum value from ['-0.0069', '-0.0201', '0.0194'] is -0.0069 来获取属性和类名作为字符串。这样,如果您获得编译时安全性,例如重命名类或属性时。像这样使用它:

nameof

详细信息:https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/nameof