Problems finding classes in namespace
I am trying to find all of the types in t开发者_运维百科he Models namespace within an ASP.NET MVC assembly from within a testing assembly. I was trying to use LINQ to find the relevant set for me but it is returning an empty set on me. I am sure it is some simple mistake, I am still relatively new to LINQ admittedly.
var abstractViewModelType = typeof (AbstractViewModel);
var baseAssembly = Assembly.GetAssembly(abstractViewModelType);
var modelTypes = baseAssembly.GetTypes()
.Where(assemblyType => (assemblyType.Namespace.EndsWith("Models")
&& assemblyType.Name != "AbstractViewModel"))
.Select(assemblyType => assemblyType);
foreach(var modelType in modelTypes)
{
//Assert some things
}
When I reach the foreach I receive a Null reference exception.
To locate a NullReferenceException
in a lot of code, you have to break it down to see what is coming back null. In your code, I only see one place where that's possible. Try this instead:
var abstractViewModelType = typeof (AbstractViewModel);
var baseAssembly = Assembly.GetAssembly(abstractViewModelType);
var modelTypes = baseAssembly.GetTypes()
.Where(assemblyType => (assemblyType.Namespace != null // Problem if null
&& assemblyType.Namespace.EndsWith("Models")
&& assemblyType.Name != "AbstractViewModel"))
.Select(assemblyType => assemblyType);
foreach(var modelType in modelTypes)
{
//Assert some things
}
精彩评论