开发者

Problems finding classes in namespace

开发者 https://www.devze.com 2022-12-26 03:46 出处:网络
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

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
}
0

精彩评论

暂无评论...
验证码 换一张
取 消