C# - LINQ 帮助

发布于 2024-09-02 01:20:33 字数 2002 浏览 2 评论 0原文

我需要检查某个类中是否存在某个属性。 请参阅相关的 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
{
}

I need to check if a certain property exists within a class.
Please refer to the LINQ query in question.
For the life of me I cannot make the compiler happy.

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

冧九 2024-09-09 01:20:33

GetProperties() 返回一个 PropertyInfo 对象。您对 p.GetType() 的调用始终会返回 typeof(PropertyInfo) - 而不是您传入的“视图”类型。

您可能需要这样:

from p in m.Value.GetType().GetProperties() 
where p.PropertyType.Equals(view) 
select p 

Edit

正如 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() 。

GetProperties() returns an array of PropertyInfo objects. Your call to p.GetType() is always going to return typeof(PropertyInfo) - never the "view" type you've passed in.

You probably want this instead:

from p in m.Value.GetType().GetProperties() 
where p.PropertyType.Equals(view) 
select p 

Edit

As Robert pointed out, your logic to determine if the above query returns any properties is also wrong. An easy way around that is to see if anything came back from the subquery:

var module = from m in Modules 
             where ( 
                 from p in m.Value.GetType().GetProperties() 
                 where p.PropertyType.Equals(view) 
                 select p 
             ).Any()
             select m

Keep in mind that that query might return more than one module. You will probably want to return .First() from the results.

杀手六號 2024-09-09 01:20:33

内部查询应返回 bool,但返回 PropertyInfo

我还没有测试过这个,但我认为你想要类似的东西:

    var module = (from m in Modules
                 where m.Value.GetType().GetProperties()
                    .Select(p => p.PropertyType).Contains(view)
                 select m).FirstOrDefault();

编辑:

在另一个答案中合并 Enumerable.Any 建议:

    var module = (from m in Modules
                 where m.Value.GetType().GetProperties()
                    .Any(p => p.PropertyType.Equals(view))
                 select m).FirstOrDefault();

The inner query should return bool, but returns PropertyInfo.

I haven't tested this, but I think you want something like:

    var module = (from m in Modules
                 where m.Value.GetType().GetProperties()
                    .Select(p => p.PropertyType).Contains(view)
                 select m).FirstOrDefault();

Edit:

Incorporating the Enumerable.Any suggestion on another answer:

    var module = (from m in Modules
                 where m.Value.GetType().GetProperties()
                    .Any(p => p.PropertyType.Equals(view))
                 select m).FirstOrDefault();
猫烠⑼条掵仅有一顆心 2024-09-09 01:20:33

where 关键字需要一个返回布尔条件的谓词,但您提供的子查询返回 IEnumerable。您可以修改您的子查询以使其返回实际的布尔条件吗?

您可以使用 FirstOrDefault() 扩展方法将其转换为布尔结果。如果没有记录,此方法将返回null。所以这应该有效(未经测试):

where ( from p in m.Value.GetType().GetProperties() 
        where p.PropertyType.Equals(view) 
        select p ).FirstOrDefault() != null

The where keyword expects a predicate that returns a boolean condition, but you are providing a subquery that returns an IEnumerable. Can you rework your subquery so that it returns an actual boolean condition?

You can convert it to a boolean result by using the FirstOrDefault() extension method. This method will return null if there are no records. So this should work (untested):

where ( from p in m.Value.GetType().GetProperties() 
        where p.PropertyType.Equals(view) 
        select p ).FirstOrDefault() != null
半葬歌 2024-09-09 01:20:33

即使您可以使查询正常工作,我也不认为这是将模型与视图链接起来的好方法。我建议创建一个新问题,更详细地说明您想要做什么(以及为什么),询问如何在模型和视图之间创建关联/链接。

Even if you can get your query working, I don't think this is a good way to link your model with your view. I'd recommend creating a new question with more detail about what you are trying to do (and why), asking how you can create the association/link between the model and the view.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文