Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get a reference to a property's setter?

Tags:

c#

.net

asp.net

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!

like image 596
nw. Avatar asked Apr 13 '11 00:04

nw.


People also ask

What is a property getter?

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.

What will happen if you bind to a property for which no public setter is available?

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.

What is getter and setter JavaScript?

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.


1 Answers

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]);
}
like image 76
Femaref Avatar answered Sep 25 '22 07:09

Femaref