I have a method that determines the concrete type to instantiate for an abstract type based on the value of a property:
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(
$"MySolution.ANamespace.InAnother.Project.Models.{concreteTypeName}, {modelType.Assembly}" );
}
}
return modelType;
}
- How can I (using reflection, probably) determine the name of the property
"MyAbstractClass.ConcreteTypeEnum"
without using a string to find it? If someone renames the property I don't want my modelbinding to break. MyAbstractClass
and the concrete classes are in the same namespace,MySolution.ANamespace.InAnother.Project.Models.*
. How can I draw that namespace from MyAbstractClass to keep from using a string here as well?
Aucun commentaire:
Enregistrer un commentaire