简体   繁体   中英

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.

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). 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. It's usually used for things like logging.

Take a look at Spring.Net or Castle Windsor .

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM