【发布时间】:2012-08-18 01:29:08
【问题描述】:
是否可以创建自定义属性(MyAttribute),以便在运行时获取 Derived.MyProperty 实际上调用 Base.GetProperty("MyProperty") 并且 Derived.MyProperty 的集合调用 Base.SetProperty("MyProperty ", 值)。
class Derived : Base
{
[MyAttribute]
string MyProperty { get; set;}
}
class Base
{
XmlDoc _xmldoc;
void SetProperty(string key, string value)
{
set key, value into _xmldoc;
}
string GetProperty(string key);
{
get key value from _xmldoc;
}
}
这是从下面的 cmets 派生的解决方案。感谢所有评论者。
public class WatchAttribute : HandlerAttribute
{
public override ICallHandler CreateHandler(IUnityContainer container)
{
return new WatchHandler();
}
}
public class WatchHandler : ICallHandler
{
public int Order { get; set; }
public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
{
Console.WriteLine(string.Format("Method '{0}' on object '{1}' was invoked.",
return getNext()(input, getNext);
}
}
public class SomeAction : MarshalByRefObject
{
[Watch]
public string MyProperty1 { get; set; }
public string MyProperty { get; set; }
}
class Program
{
static void Main(string[] args)
{
SomeAction c = new SomeAction();
IUnityContainer container = new UnityContainer()
.AddNewExtension<Interception>();
container.Configure<Interception>()
.SetInterceptorFor<SomeAction>(new TransparentProxyInterceptor())
.AddPolicy("WatchAttribute Policy")
.AddMatchingRule(new PropertyMatchingRule("*", PropertyMatchingOption.GetOrSet));
container.RegisterInstance<SomeAction>(c);
c = container.Resolve<SomeAction>();
c.MyProperty1 = "Hello";
c.MyProperty = "Hello";
}
}
【问题讨论】:
-
为什么不直接实现它们呢?
-
我正在努力为 Base 用户简化开发过程。 Base 是在工作流中从节点到节点传递的类,在每个节点上,对节点处的处理器进行编码的开发人员可以将数据添加到接收到的 Base 对象中。我试图向开发人员隐藏添加的属性实际上包含在一个 xml 文档中,并且还以一种自然的方式为开发人员完成。
-
这个问题可能会解决你的问题,如果你对 IL weaving [PostSharp aspect for property setters, calling generic method][1] [1]: stackoverflow.com/questions/246685/…
标签: c# .net custom-attributes