5

So I have a custom generic model binder, that handle both T and Nullable<T>.
But I automatically create the bindigs via reflection. I search trhough the entire appdomain for enumeration flagged with specific attribute and I want to bind theese enums like this:

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

But here is the catch. I can't bind the Nullable<T> to CommandModelBinder.
I'm thinking the runtime code generation, but I never do this, and maybe there is other options on the market. Any idea to achieve this?

Thanks,
Péter

4

1 回答 1

8

If you've got T, you can create Nullable<T> using Type.MakeGenericType:

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

I don't know how your CommandModelBinder works and what the appropriate constructor argument is, you may need

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

instead.

Note: MakeGenericType will throw an exception if called with the wrong type. I haven't added error checking, since you're already filtering to only get the types for which this makes sense. Keep this in mind if you change your filtering though.

于 2013-07-23T12:03:27.767 回答