在C#中截取调用属性的get方法 [英] Intercept call to property get method in C#

查看:312
本文介绍了在C#中截取调用属性的get方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们假设,我们有这个类:

Let's assume that we have this class:

public class Person
{
    public int Id { get; set; }
    public string Name { get; set; }
}

现在,是有可能在C#中拦截来电属性get方法,运行一些其他的方法和方法,而不是属性值的返回结果?我希望能够做一些额外的逻辑在背后。 不足之处是该类不能更改(C#的水平)。也许有的IL?

Now, is it possible in C# to intercept call to property get method, run some other method and return result of that method instead of property value? I'd like to be able to do some additional logic behind the scene. The downside is that this class can't be changed (on C# level). Maybe some IL ?

推荐答案

在.NET SDK提供了你所需要的了。您可以往返任何东西在CLR通过拆卸/重组程序(Ildasm.exe和ilasm.exe)如果你是细心。确保启动了Visual Studio命令提示符,让这些工具在路径中。

The .NET SDK has what you need already. You can round-trip most anything on the CLR by disassembly/reassembly (ildasm.exe and ilasm.exe) if you are careful. Make sure to start a "Visual Studio Command Prompt" so these tools are in your PATH.

1)反汇编person.exe

1) ildasm person.exe

2)文件 - >转储(person.il)

2) File -> Dump (person.il)

3)编辑和修改get_Name()方法: 重要提示:当在IL级修改的方法,总是重新计算的 .maxstack 的,因为在Visual Studio .NET编译器将设置它究竟是对大多数的方法,如果您添加任何code,提高。 MAXSTACK处理运行时堆栈的方法对值的最大值#,如果不是你会得到一个无效的程序。

3) Edit and modify the get_Name() method: IMPORTANT: When modifying a method at the IL level, always recalculate .maxstack, since the Visual Studio .NET compilers will have set it exactly for most methods, if you add any code, raise .maxstack to handle the maximum # of values on the runtime stack for that method, if not you'll get an invalid program.

  .method public hidebysig specialname instance string get_Name() cil managed
  {
    .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) 
    // Code size       11 (0xb)
    .maxstack  2
    .locals init (string V_0)
    IL_0000:  ldarg.0
    IL_0001:  ldfld      string Person::'<Name>k__BackingField'
    IL_0006:  stloc.0
    IL_0009:  ldloc.0
        IL_000a:  ldstr "IL code inserted here"
        call    void [mscorlib]System.Console::WriteLine(string)
    IL_001a:  ret
 } // end of method Person::get_Name

4)重新组装:ILASM person.il

4) Re-assemble : ilasm person.il

这篇关于在C#中截取调用属性的get方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆