Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
187 views
in Technique[技术] by (71.8m points)

c# - .NET Reflection: Find used types

I have been pulling my hair out trying to solve this. What I am attempting to do is to build a 'map' of how objects are being used in a bit of code I am working on. Think of it as an enhanced Find Usages. The easiest way to show this is by example:

public class MasterClass
{
    Type1 type1;
    Type2 type2;
    Type3 type3;
    void InitializeData()
    {
        type1 = new Type1(this);
        type2 = new Type2(this);
        type3 = new Type3(this);
    }
}

public class Type1
{
    private MasterClass _master;
    public Type1(MasterClass master)
    {
        _master = master;
    }
    public void Something()
    {
        //use _master.type2 and _master.type3 here
    }
}

public class Type2
{
    private MasterClass _master;
    public Type2(MasterClass master)
    {
        _master = master;
    }
    public void Something()
    {
        //use _master.type3 here
    }
}

public class Type3
{
    private MasterClass _master;
    public Type3(MasterClass master)
    {
        _master = master;
    }
    public void Something()
    {
        //use _master.type1 and _master.type2 here
    }
}

What I am trying to do is get a mapping or report that, in the example's case, would give something like:

Type1 used by: {Type3}

Type2 used by: {Type1, Type3}

Type3 used by: {Type1, Type2}

If I can get it into a dictionary then I am home. :-)

What I've tried:

I have tried going over the assemblies, each type, each method then pulling the IL arrays and then trying to parse the operands with no luck. I have even tried going over the source files with some regular expressions but I have thousands of classes to go over, written in several different styles which means I will missed some references.

I can use Reflector &&/|| Resharper to get a single reference at a time but I would like to get them all at once.

Any suggestions?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I suggest using NDepend for this, as it is tailor made to the problem you're describing. Doing this in code is going to be quite a lot of work.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...