gpt4 book ai didi

c# - 通用类型的 ASP.NET MVC 模型绑定(bind)器

转载 作者:IT王子 更新时间:2023-10-29 04:43:28 24 4
gpt4 key购买 nike

是否可以为通用类型创建模型绑定(bind)器?例如,如果我有一个类型

public class MyType<T>

有没有办法创建适用于任何类型的 MyType 的自定义模型绑定(bind)器?

谢谢,弥敦道

最佳答案

创建一个modelbinder,覆盖BindModel,检查类型并做你需要做的事情

public class MyModelBinder
: DefaultModelBinder {

public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) {

if (HasGenericTypeBase(bindingContext.ModelType, typeof(MyType<>)) {
// do your thing
}
return base.BindModel(controllerContext, bindingContext);
}
}

将模型绑定(bind)器设置为 global.asax 中的默认值

protected void Application_Start() {

// Model Binder for My Type
ModelBinders.Binders.DefaultBinder = new MyModelBinder();
}

检查匹配的通用碱基

    private bool HasGenericTypeBase(Type type, Type genericType)
{
while (type != typeof(object))
{
if (type.IsGenericType && type.GetGenericTypeDefinition() == genericType) return true;
type = type.BaseType;
}

return false;
}

关于c# - 通用类型的 ASP.NET MVC 模型绑定(bind)器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1487005/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com