Is there a way to intercept setters and getters in

2020-03-01 04:05发布

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.

11条回答
The star\"
2楼-- · 2020-03-01 04:27

You will have to write the properties in full to achieve this.

查看更多
家丑人穷心不美
3楼-- · 2020-03-01 04:32

Yes, you may use the Decorator Design Pattern.

查看更多
叼着烟拽天下
4楼-- · 2020-03-01 04:38

Yes, of course...

In your example you are using automatic properties, without a backing field.... You just need to create a backing field for your property, and then you can do what you want in the setter and getter.

example:

private string firstName;

public string FirstName
{
 get { return firstName; }

 set { doMethod(); firstName = value;}
}
查看更多
Emotional °昔
5楼-- · 2020-03-01 04:39

I know this has been properly answered but I'll include an example to show you the syntax to achieve what you want:

public class Person
{
    private 
    public string FirstName
    {
        get
        {
            return _firstName;
        }
        set
        {
            // see how we can call a method below? or any code for that matter..
            _firstName = SanitizeName(value);
        }
    }
}
查看更多
不美不萌又怎样
6楼-- · 2020-03-01 04:40

Mocking frameworks can do this, as well as IoC libraries like Unity. The only other way to do such a thing would be to use IL-rewriting (as previously mentioned).

查看更多
仙女界的扛把子
7楼-- · 2020-03-01 04:40

You cant use automatic properties. You would have to dinfe the property out the old fashion way with a backing field and call the method manually.

public class Person
{
    private string _FirstName;
    public string FirstName 
    { 
        get
        {
            return _FirstName;
        }
        set
        {
            SomeMethod();
            _FirstName = value;
        }
    }
    private void SomeMethod()
    {
        //do something
    }

}
查看更多
登录 后发表回答