I have some asp.net code that populates the fields in a LINQ to SQL object (all string fields) with values from a posted form:
userSelections.A = Request.Form["A"];
userSelections.B = Request.Form["B"];
userSelections.C = Request.Form["C"];
userSelections.D = Request.Form["D"];
I want to store the name of the form field and the associated setter object in a table, so I can iterate through the whole set without having to write a bunch of repeating code.
Is there a way to get a delegate to a property setter? i.e., say I have class myClass, with string property myProperty. Can I get a delegate, something like void myPropertySetterDelegate(string val, MyClass this), that can be used with any instance of the class?
I know this can be done with reflection, but other developers on my project have performance concerns, so I would prefer a non-reflection solution if possible.
Thanks!
Getters: These are the methods used in Object-Oriented Programming (OOPS) which helps to access the private attributes from a class. Setters: These are the methods used in OOPS feature which helps to set the value to private attributes in a class.
If no getter or setter for the field exists, a direct access for the field is performed. If a getter exists for the field, it will be executed when trying to read the field from outside.
Getter — binds an object property to a function that will be called when that property is looked up. Setter — binds an object property to a function to be called when there is an attempt to set that property. They give you a way of defining a property but do not calculate the property's value until it is accessed.
You can use a lambda:
Action<MyClass, string> myPropertySetter = (mc, s) => mc.MyProperty = s;
And you have an instance of MyClass
:
MyClass something = repo.GetMyClass();
myPropertySetter(something, valueFromSomewhere);
Now, following your example:
Dictionary<string, Action<MyClass, string>> setters = new Dictionary<string, Action<MyClass, string>>();
setters.Add("A", Action<MyClass, string> myPropertySetter = (mc, s) => mc.A = s);
[...]
Later:
MyClass something = getFromSomewhere();
foreach (string key in Request.Form.Keys)
{
setters[key](something, Request.Form[key]);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With