用Nullable<;T>;通过反射

本文关键字:反射 gt lt Nullable | 更新日期: 2023-09-27 18:24:19

所以我有一个自定义的通用模型绑定器,它同时处理T和Nullable<T>
但我通过反射自动创建了bindigs。我在整个应用程序域中搜索标记有特定属性的枚举,我想像这样绑定这些枚举:

  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
    });

但问题是。我无法绑定Nullable<T>到CommandModelBinder
我在考虑运行时代码生成,但我从来没有这样做过,也许市场上还有其他选择。有实现这一目标的想法吗?

谢谢,
Péter

用Nullable<;T>;通过反射

如果您有T,您可以使用Type.MakeGenericType:创建Nullable<T>

ModelBinders.Binders.Add(t, new CommandModelBinder(t));
var n = typeof(Nullable<>).MakeGenericType(t);
ModelBinders.Binders.Add(n, new CommandModelBinder(n));

我不知道你的CommandModelBinder是如何工作的,也不知道合适的构造函数参数是什么,你可能需要

ModelBinders.Binders.Add(n, new CommandModelBinder(t));

相反。

注意:如果使用错误的类型调用,MakeGenericType将引发异常。我还没有添加错误检查,因为您已经在过滤,只获取有意义的类型。不过,如果您更改了筛选,请记住这一点。