
interface IUserData { User GetUser(uint ID); User Byname(string username);}class UserData : IUserData { ...}class AuthorizedUserData : IUserData { IUserData _Data = new UserData(); public User GetUser(uint ID) { AuthorizationHelper.Instance.Authorize(); return _Data.GetUser(ID); } public User Byname(string name) { AuthorizationHelper.Instance.Authorize(); return _Data.Byname(name); }} 所以基本设置是:
>创建一个界面
>创建一个实际实现该接口的具体类
>为该类创建一个包装器,在调用具体类之前执行相同的工作
鉴于这些类实现了相同的接口,并且在包装类的每个方法的开头完成了完全相同的工作,这使我认为我可以自动化这个包装过程.
我知道在JavaScript和Python中创建这样的装饰器是可能的.
JavaScript中的示例:
function AuthorizedUserData() { ...}const userDataPrototype = Object.getPrototypeOf(new UserData());Object.getownPropertynames(userDataPrototype) .forEach(name => { const val = userDataPrototype[name]; if (typeof val !== 'function') { return; } AuthorizedUserData.prototype[name] = function(...args) { AuthorizationHelper.Authorize(); return this._Data[name](...args); }; }); 在C#中这种自动实现是否可行?
解决方法 使用任何依赖注入(DI)框架.以下使用WindsorCastle.使用nuget安装温莎城堡.
拦截器可以在您的场景中用于拦截对方法的任何请求.
可以通过实现IInterceptor来创建拦截器
public class AuthorizedUserData : IInterceptor{ public voID Intercept(IInvocation invocation) { //Implement valIDation here }} 使用DI容器注册依赖项并注册拦截器和类
var container = new WindsorContainer();container.Register(Castle.MicroKernel.Registration.Component.For<AuthorizedUserData>().lifestyleSingleton());container.Register( Castle.MicroKernel.Registration .Classes .FromAssemblyInThisApplication() .BasedOn<IUserData>() .WithServiceAllinterfaces().Configure( x => x.Interceptors<AuthorizedUserData>()));
您的类和接口结构如下所示
public interface IUserData { User GetUser(uint ID); User Byname(string username); } public class UserData : IUserData { public User GetUser(uint ID) { throw new System.NotImplementedException(); } public User Byname(string username) { throw new System.NotImplementedException(); } } public class User { } 然后使用DI容器来解析您需要的实例.这里我们需要一个IUserData实例
var user = container.Resolve<IUserData>(); // Creates an instance of UserDatauser.Byname("username"); //This call will first goto `Intercept` method and you can do valIDation. 总结 以上是内存溢出为你收集整理的c# – 自动实现装饰器方法全部内容,希望文章能够帮你解决c# – 自动实现装饰器方法所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)