Pét*_*ter 5 .net c# asp.net-mvc model-binding system.reflection
所以我有一个自定义通用模型绑定器,它同时处理T和Nullable <T>.
但我通过反射自动创建bindigs.我搜索整个应用程序域以查找标记有特定属性的枚举,并且我想要像这样绑定theese枚举:
AppDomain
.CurrentDomain
.GetAssemblies()
.SelectMany(asm => asm.GetTypes())
.Where(
t =>
t.IsEnum &&
t.IsDefined(commandAttributeType, true) &&
!ModelBinders.Binders.ContainsKey(t))
.ToList()
.ForEach(t =>
{
ModelBinders.Binders.Add(t, new CommandModelBinder(t));
//the nullable version should go here
});
Run Code Online (Sandbox Code Playgroud)
但这是抓住了.我无法将Nullable <T>绑定到CommandModelBinder.
我正在考虑运行时代码的生成,但我从来没有这样做,也许市场上还有其他选择.任何想法实现这一目标?
谢谢,
Péter
小智 8
如果你有T,你可以创建Nullable<T>使用Type.MakeGenericType:
ModelBinders.Binders.Add(t, new CommandModelBinder(t));
var n = typeof(Nullable<>).MakeGenericType(t);
ModelBinders.Binders.Add(n, new CommandModelBinder(n));
Run Code Online (Sandbox Code Playgroud)
我不知道你的CommandModelBinder工作方式以及适当的构造函数参数是什么,你可能需要
ModelBinders.Binders.Add(n, new CommandModelBinder(t));
Run Code Online (Sandbox Code Playgroud)
代替.
注意:MakeGenericType如果使用错误的类型调用,将抛出异常.我没有添加错误检查,因为您已经过滤到只获取有意义的类型.如果您更改过滤,请记住这一点.