使用属性生成定制的setter [英] Generate custom setter using attributes

查看:187
本文介绍了使用属性生成定制的setter的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在其实例上仍然存在我使用一个对象数据库,我一直有这样做:

In classes whose instances I persist using an object database, I keep having to do this:

private string _name;
public string Name
    {
    get { return this._name; }
    set { _name = value; this.Save(); }
    }

而我宁愿键入以下内容:

whereas I would much rather type this:

[PersistedProperty(Name)]
private string _name;

其中PersistedProperty属性生成getter和setter就像默认的[属性()]属性,但我想要一条线code的增加所产生的二传手。

where the PersistedProperty attributes generates a Getter and Setter just like the default [Property()] attribute, except I want to add a line of code to the generated Setter.

有没有一种方法,我可以创建一个做到这一点的属性?但愿,这与智能感知的作品。

Is there a way I can create an attribute which does this? Hopefully , which works with Intellisense.

如何默认的[属性()]属性连做它的东西?如果我看到了code,我可以移植物...

How does the default [Property()] attribute even do it's stuff? If I saw the code I could graft that...

请注意:我其实这样做的嘘声,但认为我给C#code为更多的人可能会愿意回答这个问题,但是,如果有一个驸具体的解决方案,我所有的耳朵!

Note: I am actually doing this in Boo, but thought I'd give c# code as more people might be willing to answer that, however, if there is a Boo specific solution, I'm all ears!

更新:

我的目的很简单就是减少打字和混乱。事实证明这样做是有其产生在我的课的基础上的标记部分类的脚本的最简单的方法。

My aim was simply to reduce typing and clutter. It turns out the simplest way of doing this was with a script which generates partial classes based on markup in my classes.

自动生成的标记源$ C ​​$ C(与部分类串联)是容易的,实际上看起来像一个非常有前途的方式来避开一些问题,我们通常尝试用继承和泛型类型。解决

Auto-generating source code from markup (in tandem with partial classes) is easy, and actually looks like an extremely promising way to get round some of the problems we normally try to solve with inheritance and generic types.

推荐答案

这需要面向方面的编程。虽然.NET不直接支持,它可以通过第三方工具,如 PostSharp 来完成。

This requires aspect oriented programming. While not directly supported in .NET, it can be done via third party tooling, such as PostSharp.

有关智能感知工作,然而,这必须在图书馆做,因为(最终)编译code将展开到全属性的getter / setter方法​​。

For intellisense to work, however, this must be done in a library, as the (final) compiled code will be unrolled into the full property getter/setter.

这篇关于使用属性生成定制的setter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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