如何使用“委托”创建属性访问器?
我是 C# 新手,几天来一直对此感到困惑。基本上我想创建一个 type 属性,并将 getter 和 setter 逻辑委托给该参数所属的基本类型。
这只是一个应用程序:其值由注册表或某个配置文件等设置的属性。
- get 上的属性处理程序会执行一些操作,例如检查缓存的值(或不检查)、检索该值(如果未缓存)、缓存该值(或不缓存)并返回它。
- 设置器的行为将仅允许属性处理程序设置值(如果可能)。
有什么建议吗?我考虑过使用 DefaultPropertyAttribute
,但我不太明白如何不编写每个访问器所需的所有逻辑。
看起来这就是我想要的:http://www.sharpcrafters.com/postsharp
“少写代码“ 是的。就这样吧。
I'm new to c# and have been puzzling over this for a couple of days. Basically I want to create a type of property with getter and setter logic delegated to a base type to which this parameter belongs.
This is just one application: a property whose value is set by, say, the registry or some config file.
- The property handler on a get would do something like check a cached value (or not), retrieve the value if not cached, cache the value (or not) and return it.
- Behavior for the setter would allow only the property handler to set the value (if possible).
Any suggestions? I've thought about using DefaultPropertyAttribute
, but I can't quite see how not to write all the logic necessary with each accessor.
Looks like this is what I want: http://www.sharpcrafters.com/postsharp
"Write less code" Yup. That's it alright.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我并不为此感到自豪:
100% 未经测试。
更新结合使用上述内容和@hunter的答案,您可以执行以下操作:
有了这个,您现在可以执行以下操作:
I'm not proud of it:
100% untested.
UPDATE Using a combination of the above, and @hunter's answer, you could do something like:
With that, you can now do something like:
使用这个愚蠢的类:
你可以做这样的事情:
当然,这不能处理所有情况,但它可能会让你走上“正确”的轨道......
Using this stupid class:
you can do something like this:
Of course this won't handle every case but it might get you on the "right" track...