I am trying to use reflection to get classes based on the interface name. But when I try to create an instance of the class based on the type using CreateInstance() I am receiving the error CS8600 Converting null literal or possible null value to non-nullable type.
public RequestEmailNotifyBehaviour()
{
IEnumerable<Type> emailNotifiers = GetTypesWithInterface(Assembly.GetExecutingAssembly());
List<IEmailNotification<IRequest>> listOfNotifiers = new List<IEmailNotification<IRequest>>();
foreach (Type type in emailNotifiers)
{
listOfNotifiers.Add((IEmailNotification<IRequest>)Activator.CreateInstance(type));
}
}
private IEnumerable<Type> GetTypesWithInterface(Assembly asm)
{
var it = typeof(IEmailNotification<TRequest>);
return asm.GetLoadableTypes()
.Where(it.IsAssignableFrom)
.Where(t => !(t.Equals(it)))
.ToList();
}
public static class TypeLoaderExtensions
{
public static IEnumerable<Type> GetLoadableTypes(this Assembly assembly)
{
if (assembly == null) throw new ArgumentNullException("assembly");
try
{
return assembly.GetTypes();
}
catch (ReflectionTypeLoadException e)
{
return (IEnumerable < Type > ) e.Types.Where(t => t != null);
}
}
}
Aucun commentaire:
Enregistrer un commentaire