如何避免在我的 MVC CustomModelBinding 中使用魔术字符串?
How Can I Avoid Using Magic Strings in my MVC CustomModelBinding?
我有一个方法可以根据 属性 的值确定要为抽象类型实例化的具体类型:
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"
的名称而不使用字符串来查找它?如果有人重命名 属性,我不想破坏我的模型绑定。
我在想
var key = modelType.GetProperty(t => t.ConcreteTypeEnum).Name
...但不存在这样的生物。
您可以使用 nameof
获取 属性 和 class 名称作为字符串。这样,如果您获得编译时安全性,例如重命名 class 或 属性 时。像这样使用它:
var propertyName = nameof(MyAbstractClass.ConcreteTypeEnum);
// propertyName is now "ConcreteTypeEnum"
var className = nameof(MyAbstractClass);
// className is now "MyAbstractClass"
详情:https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/nameof
我有一个方法可以根据 属性 的值确定要为抽象类型实例化的具体类型:
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"
的名称而不使用字符串来查找它?如果有人重命名 属性,我不想破坏我的模型绑定。
我在想
var key = modelType.GetProperty(t => t.ConcreteTypeEnum).Name
...但不存在这样的生物。
您可以使用 nameof
获取 属性 和 class 名称作为字符串。这样,如果您获得编译时安全性,例如重命名 class 或 属性 时。像这样使用它:
var propertyName = nameof(MyAbstractClass.ConcreteTypeEnum);
// propertyName is now "ConcreteTypeEnum"
var className = nameof(MyAbstractClass);
// className is now "MyAbstractClass"
详情:https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/nameof