【问题标题】:Find direct & indirect method usages if method is overriden in base class查找方法的直接和间接方法用法在基类中被覆盖
【发布时间】:2016-06-09 13:24:36
【问题描述】:

请帮我弄清楚如何编写查询:)

代码是:

namespace ConsoleApplication1
{
    class Program
    {
        static void Main()
        {
            var man = new Man("Joe");

            Console.WriteLine(man.ToString());
        }
    }

    public class SuperMan
    {
        public SuperMan(string name)
        {
            this.name = name;
        }

        public override string ToString()
        {
            return name;
        }

        string name;
    }

    public class Man : SuperMan
    {
        public Man(string name) : base(name)
        {
        }
    }
}

我想找到 Man.ToString() 的所有直接和间接依赖项(方法)。 Main() 方法中只有一个调用。

我正在尝试的查询是:

from m in Methods 
let depth0 = m.DepthOfIsUsing("ConsoleApplication1.SuperMan.ToString()")
where depth0  >= 0 orderby depth0
select new { m, depth0 }.

但它没有找到依赖的 Program.Main() 方法......

如何修改查询以找到此类方法的用法?

【问题讨论】:

    标签: ndepend


    【解决方案1】:

    首先让我们看看直接调用者。我们想列出所有调用SuperMan.ToString() 的方法或任何被SuperMan.ToString() 覆盖的ToString() 方法。它看起来像:

    let baseMethods = Application.Methods.WithFullName("ConsoleApplication1.SuperMan.ToString()").Single().OverriddensBase
    from m in Application.Methods.UsingAny(baseMethods)
    where m.IsUsing("ConsoleApplication1.Man")  // This filter can be added
    select new { m, m.NbLinesOfCode }
    

    注意我们放置了一个过滤子句,因为在现实世界中几乎每个方法都调用object.ToString()(这是一个特殊情况)。

    现在处理间接调用更加棘手。我们需要在泛型序列上调用魔术FillIterative() 扩展方法。

    let baseMethods = Application.Methods.WithFullName("ConsoleApplication1.SuperMan.ToString()").Single().OverriddensBase
    let recursiveCallers = baseMethods.FillIterative(methods => methods.SelectMany(m => m.MethodsCallingMe))
    
    from pair in recursiveCallers 
    let method = pair.CodeElement
    let depth = pair.Value
    where method.IsUsing("ConsoleApplication1.Man") // Still same filter
    select new { method , depth }
    

    等等!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-13
      • 2021-08-12
      • 2016-01-27
      • 1970-01-01
      • 2013-11-14
      • 1970-01-01
      相关资源
      最近更新 更多