处理对对象属性的每个 get 或 set 调用 [英] Handle every get or set call to objects properties

查看:34
本文介绍了处理对对象属性的每个 get 或 set 调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种在访问属性 getter 和 setter 时自动检查访问权限的好方法.

I am searching for a good approach to automatically check the access rights when accessing a propertys getter and setter.

这只是出于好奇和实验目的,因此性能并不重要.

This is just for curiosity and experimental purposes, so performance does not really matter.

我发现的一种方法如下(示例仅适用于 getter):

One Approach I found is the following (example is just for getters):

public class DynamicPropertyClass : DynamicObject
{
    /// <summary>
    /// I want this to work for a default auto-property
    /// </summary>
    public string TestString { get; set; }

    public override bool TryGetMember(GetMemberBinder binder, out object result)
    {
        if (StaticSecurityContext.CheckSecurityCondition(binder.GetType(), binder.Name))
        {
            return base.TryGetMember(binder, out result);
        }
        else
        {
            throw new SecurityException();
        }
    }
}

如果未给出安全条件,则使用动态对象中止.这种方法的问题在于,类中实际存在的属性不会被 TryGetMember 方法处理.所以这种方法迫使我只处理代码中实际上不存在的属性.

Using a dynamic object to abort if the Security Conditions are not given. The problem with this approach is that properties that actually exist on the class won't get handled by the TryGetMember method. So this approach forces me to only handle properties that do not actually exist in code.

如您所见,动态功能与我的方法并不真正相关.我想要一些类似的东西来处理我用代码编写的属性,不必支持动态功能.

As you can see the dynamic capabilitys are not really relevant for my approach. I want something similar to work on my properties written in code, dynamic capabilitys do not have to be supported.

那么,是否有另一种方法可以在 c# 中实现,无需在每个属性上应用属性或向 getter 和 setter 添加自定义代码?

So, is there another approach, possible in c#, without applying attributes on every property or adding custom code to the getters and setters?

推荐答案

您可以使用代理模式.AOP框架提供了很多实现,但是如果性能不是条件,你可以简单地尝试远程API使用的Transparent/RealProxy.

You can use a proxy pattern. It exist a lot of implemention provided by AOP framework but if performance is not condition, you can simply try Transparent/RealProxy used by remoting API.

https://msdn.microsoft.com/fr-fr/library/system.runtime.remoting.proxies.realproxy(v=vs.110).aspx

这篇关于处理对对象属性的每个 get 或 set 调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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