【问题标题】:Check via reflection if specific extension method is used inside the method通过反射检查方法内部是否使用了特定的扩展方法
【发布时间】:2014-09-06 23:28:31
【问题描述】:

我在徘徊,如果我在某些 DLL 中有这样的代码:

public class DemoClass
{
    public void TestAction(XMParams command)
    {
        var firstName = command.Parse<string>(Params.First, "First Name");
        var lastName = command.Parse<string>(Params.Second, "Last Name");

        var userData = new UserDataDto{
            FirstName = firstName,
            LastName = lastName
        }

        command.StoreValue(userData, "User Data");
    }
}

是否可以检测到使用 command.Parse 的这些行,并提取这些数据: command.ParseType>(Index, Description)

command.StoreValue(Type, DescriptiveName);

如下所示的对象列表:

public class InputParamObj
{
    public int Index {get;set;}
    public string Type {get;set;}
    public string Description {get;set;}
}
public class OutputObj
{
    public string Type {get;set;}
    public string Description {get;set;}
}
public class CommandData
{
    public List<InputParamObj> InputParams {get;set;}
    public OutputObj Output {get;set;}
}

注意,这段代码总是在已知方法中,例如在“TestAction”方法中。

【问题讨论】:

  • 听起来根本不是反射任务。 Reflection 是一个元数据 API,允许获取有关类型、方法等的信息,而不是关于如何以及从何处调用它们的信息。我想你想要的叫做拦截,是另一个世界。请在此处查看这些技术的一个示例 (msdn.microsoft.com/en-us/library/dn178466(v=pandp.30).aspx)

标签: c# .net reflection


【解决方案1】:

你不想通过反射来做那种事情。使用MethodInfo.GetMethodBody(),您可以获得用于方法实现的二进制 IL Stream,但祝您好运。

您需要解析您的代码。检查this 以查看一个不错的解决方案列表。他们中的大多数都很好,这取决于您的实际需求。我个人会选择Roslyn,这是微软新推出的“编译器即服务”,因为据我所见,它确实是一个很棒的 api:功能强大且编写得非常好。但它现在可能不适合您的需求。

【讨论】:

  • 谢谢,我在看 Mono.Cecil,真的很棒!我将不得不做一些手工和肮脏的工作来获得我想要的东西,但它可以完成。如果我找到更好的方法,我会告诉你的。
猜你喜欢
  • 1970-01-01
  • 2012-11-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多