[英]Using an attribute to update an object passed as a parameter
I have done a bit with C# method attributes but I have not done something that covers this requirement, and I am not even sure it is possible but here goes. 我已经对C#方法属性做了一些工作,但是还没有完成满足此要求的工作,我什至不确定是否可行,但是可以。
Let say I have a class like.. 假设我有一个类似的课程。
public class MyObject
{
public DateTime? TheTime {get;set;}
public string AValue {get;set;}
}
And a function like this... 还有这样的功能
public void AddObject(MyObject mo)
{
//Do Something
}
Now, when the object is passed AValue will be set, but TheTime will be null (as this needs to be set in the AddObject method). 现在,当对象被传递时,将设置AValue,但TheTime将为null(因为需要在AddObject方法中进行设置)。 I can do this like... 我可以这样...
public void AddObject(MyObject mo)
{
mo.TheTime = DateTime.Now;
//Do Something
}
But I don't like that, what I want is to create an attribute that will do the job for me. 但是我不喜欢这样,我想要的是创建一个可以为我完成工作的属性。 So ultimately, I want something like this 所以最终,我想要这样的东西
[AutoUpdate(Parameter = "mo")]
public void AddObject(MyObject mo)
{
//Do Something
}
and the magic is done for me. 而魔术为我做。
Any ideas on how to create an attribute to do this? 关于如何创建属性以执行此操作的任何想法? A simple link would do, I can't seem to find what I am looking for at the minute 一个简单的链接就可以了,我似乎暂时找不到我想要的东西
You can achieve this with a cross-cutting concerns library ( AOP ), which applies a decorator pattern around your method, allowing you to inject functionality via attributes. 您可以使用横切关注点库( AOP )实现此目的,该库在您的方法周围应用了一个装饰器模式 ,从而允许您通过属性注入功能。 It's usually used for things like logging. 通常用于日志记录之类的东西。
Take a look at Spring.Net or Castle Windsor . 看看Spring.Net或温莎城堡 。
A a quick example of decorator pattern to create your own implementation. 一个创建您自己的实现的装饰器模式的快速示例。
public class MyExtendedClass : IMyClass
{
public MyExtendedClass(IMyClass myClass)
{
this.innerMyClass= myClass;
}
public void AddObject(MyObject mo)
{
// does mo have an attribute on AddObject
// if so
Type clsType = innerMyClass.GetType();
MethodInfo mInfo = clsType.GetMethod("AddObject");
if (Attribute.IsDefined(mInfo, typeof(AutoUpdateAttribute)))
{
mo.TheTime = DateTime.Now;
}
innerMyClass.AddObject(mo);
}
}
Then use like this: 然后像这样使用:
IMyClass myClass = new MyExtendedClass(new MyClass());
myClass.AddObject(mo);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.