Generate custom setter using attributes

后端 未结 2 1118
有刺的猬
有刺的猬 2021-02-15 23:31

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._na         


        
2条回答
  •  轮回少年
    2021-02-16 00:17

    Not easy to implement using attributes IMO. Maybe you could use another approach, such as an extension method:

    // Extension method that allows updating a property
    // and calling .Save() in a single line of code.
    public static class ISaveableExtensions
    {
        public static void UpdateAndSave(
            this ISaveable instance,
            Expression> propertyExpression, T newValue)
        {
            // Gets the property name
            string propertyName = ((MemberExpression)propertyExpression.Body).Member.Name;
    
            // Updates its value
            PropertyInfo prop = instance.GetType().GetProperty(propertyName);
            prop.SetValue(instance, newValue, null);
    
            // Now call Save
            instance.Save();
        }
    }
    ...
    // Some interface that implements the Save method
    public interface ISaveable
    {
        void Save();
    }
    ...
    // Test class
    public class Foo : ISaveable
    {
        public string Property { get; set; }
    
        public void Save()
        {
            // Some stuff here
            Console.WriteLine("Saving");
        }
    
        public override string ToString()
        {
            return this.Property;
        }
    }
    ...
    public class Program
    {
        private static void Main(string[] args)
        {
            Foo d = new Foo();
    
            // Updates the property with a new value, and automatically call Save
            d.UpdateAndSave(() => d.Property, "newValue");
    
            Console.WriteLine(d);
            Console.ReadKey();
        }
    }
    

    It's type-safe, autocompletion-friendly, but it requires more code than just .Save() in all setters, so not sure I would use it actually...

提交回复
热议问题