有没有一种方法可以拦截C#中的setter和getter? [英] Is there a way to intercept setters and getters in C#?

查看:164
本文介绍了有没有一种方法可以拦截C#中的setter和getter?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Ruby和PHP中(我猜也可能是其他语言),只要设置了属性,就会调用一些实用程序方法. (对于Ruby为 * instance_variable_set * ,对于PHP为 * __ set * ).

所以,假设我有一个像这样的C#类:

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

现在,假设如果调用了Person类中的任何属性设置器,我想先调用另一个方法,然后继续使用该设置器的默认行为,这同样适用于属性设置器. /p>

这可能吗?


我想在不定义背景字段的情况下执行此操作.

解决方案

一般而言;几个选项;

  • 继承自 ContextBoundObject -它是做的允许这样做,但会降低性能
  • 编写一个显式属性(即具有后备字段),然后手动添加实用程序方法调用
  • 查看编译时织工,例如 PostSharp -通常是通过发现属性或类似属性
  • 看看一些DI/IoC工具(和一些其他基于"decorator"的工具)提供的运行时代码生成器-它们可以修饰或子类化您的对象以添加额外的代码

In both Ruby and PHP (and I guess other languages as well) there are some utility methods that are called whenever a property is set. ( *instance_variable_set* for Ruby, *__set* for PHP).

So, let's say I have a C# class like this:

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

Now, let's say that if any property setter from the Person class is called, I want to call another method first, and then continue with the default behaviour of the setter, and the same applies for the property setters.

Is this possible?


Edit: I want to do this without defining a backing field.

解决方案

Not generally; a few options though;

  • inherit from ContextBoundObject - which does allow this, but at a performance cost
  • write an explicit property (i.e. with a backing field), and add a utility method call manually
  • look at compile-time weavers, such as PostSharp - generally by spotting an attribute or similar
  • look at runtime code generators, as offered by some DI/IoC tools (and some other "decorator" based tools) - which either decorate or subclass your object to add the extra code

这篇关于有没有一种方法可以拦截C#中的setter和getter?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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