【问题标题】:How Can I Avoid Using Magic Strings in my MVC CustomModelBinding?如何避免在 MVC CustomModelBinding 中使用魔术字符串?
【发布时间】:2019-02-03 20:08:28
【问题描述】:

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

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 

...但不存在这样的小动物。

【问题讨论】:

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


    【解决方案1】:

    您可以使用nameof 以字符串形式获取属性和类名。这样,如果您获得编译时安全性,例如重命名类或属性时。像这样使用它:

    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

    【讨论】:

    • 好吧,把我绑在猪身上,把我滚进泥里。我不会认为这会起作用,因为 ConcreteTypeEnum 不是静态的......但它确实如此!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-20
    相关资源
    最近更新 更多