1

The context of this question is too elaborate to describe here and will likely adversely affect responses so I am not including it. I want to assert certain things about a method in a unit test. Some of these things are possible using reflection such as format of the try/finally block, class fields and method local variables, etc. I already know the type and method signature.

    protected override void OnTest ()
    {
        bool result = false;
        SomeCOMObject com = null; // System.__ComObject

        try
        {
        }
        finally
        {
            System.Runtime.InteropServices.Marshal.ReleaseComObject(com);
        }

        return (result);
    }

What I have not been able to achieve are things like:

  • Whether the method contains only a single return (result); statement and whether that statement is the last one in the function.
  • Whether all variables of type System.__ComObject have been manually de-referenced using System.Runtime.InteropServices.Marshal.ReleaseComObject(object) in the finally block.

Since some of these things are not possible using reflection, and source code text analysis is far from ideal, I turned to CodeDom but have not been able to get a grip on it. I have been told that creating expression trees from source code is not possible. Nor is it possible to create expression trees from the runtime type. If that is correct, how can I leverage CodeDom to achieve things in the list above?

I have used CodeDom in the past for code generation and compiling simple code classes to assemblies. But I have no idea how it could be used to analyze the internals of a method. Please advise.

4

1 回答 1

2

通常,编程语言中内置的反射不提供对函数内容的访问。所以你几乎不能通过反射来做到这一点。

如果您可以访问等效的字节码,您也许可以做到这一点,但字节码不能真正回答有关方法语法的问题,例如,“存在多少返回语句返回相同的表达式”。

如果你想推理代码,你需要推理代码。这意味着您需要访问解析器,并且通常需要访问其他有用的事实(“X 的声明是什么?”、“X 和 Y 的类型是否兼容?”、“数据是否从 X 流向 Y?”)等。

Roslyn 提供了其中的一些信息。还有商业解决方案(我有一个)。

于 2013-05-13T17:46:31.740 回答