我需要检查类中是否存在某个属性。 请参阅有问题的 LINQ 查询。 我这辈子都无法让编译器开心。
class Program
{
static void Main(string[] args)
{
ModuleManager m = new ModuleManager();
IModule module = m.FindModuleForView(typeof(HomeView));
Console.WriteLine(module.GetType().ToString());
Console.ReadLine();
}
}
public class ModuleManager
{
[ImportMany]
public IEnumerable<Lazy<IModule>> Modules { get; set; }
[ImportMany]
public IEnumerable<Lazy<View>> Views { get; set; }
public ModuleManager()
{
//An aggregate catalog that combines multiple catalogs
var catalog = new AggregateCatalog();
//Adds all the parts found in the same assembly as the Program class
catalog.Catalogs.Add(new AssemblyCatalog(typeof(Program).Assembly));
//Create the CompositionContainer with the parts in the catalog
_container = new CompositionContainer(catalog);
//Fill the imports of this object
try
{
this._container.ComposeParts(this);
}
catch (CompositionException compositionException)
{
Console.WriteLine(compositionException.ToString());
}
}
public IModule FindModuleForView(Type view)
{
//THIS IS THE PROBLEM
var module = from m in Modules
where (
from p in m.Value.GetType().GetProperties()
where p.GetType().Equals(view)
select p
)
select m;
}
public CompositionContainer _container { get; set; }
}
public interface IModule
{
}
[Export]
public class HomeModule : IModule
{
public HomeModule()
{
}
[Export]
public HomeView MyHomeView
{
get
{
return new HomeView();
}
set
{
}
}
}
public class HomeView : View
{
}
public class View
{
}
最佳答案
GetProperties()返回 PropertyInfo 的数组对象。您对 p.GetType() 的调用总是会返回 typeof(PropertyInfo) - 而不是您传入的“ View ”类型。
你可能想要这个:
from p in m.Value.GetType().GetProperties()
where p.PropertyType.Equals(view)
select p
编辑
正如 Robert 所指出的,您确定上述查询是否返回任何属性的逻辑也是错误的。一个简单的解决方法是查看子查询是否返回任何内容:
var module = from m in Modules
where (
from p in m.Value.GetType().GetProperties()
where p.PropertyType.Equals(view)
select p
).Any()
select m
请记住,该查询可能会返回多个模块。您可能希望从结果中返回 .First()。
关于C# - LINQ 帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2878969/