Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Below, I've written a wrapper class you can use to set/get public fields or properties of the wrapped class by string name.</p> <p>First, let's look at how you could use it on a class that had the public fields or properties StartDate and SocialSecurityNumber.</p> <pre><code>// First create the instance we'll want to play with MyUserControl myControlInstance = new MyUsercontrol(); // MyUserContol has two properties we'll be using // DateTime StartDate // int SocialSecurityNumber // Now we're creating a map to facilitate access to the properties // of "myControlInstance" using strings PropertyMap&lt;MyUserControl&gt; map = new PropertyMap&lt;MyUserControl&gt;(myControlInstance); // Since the map is directed toward "myControlInstance" // this line is equivalent to: // myControlInstance.StartDate = Datetime.Now; map.Set&lt;DateTime&gt;("StartDate", DateTime.Now); // This line is equivalent to: // ssn = myUsercontrol.SocialSecurityNumber; int ssn = map.Get&lt;int&gt;("SocialSecurityNumber"); </code></pre> <p>And now on to how it's implemented:</p> <pre><code>public class PropertyMap&lt;T&gt; { readonly T Instance; public PropertyMap(T instance) { Instance = instance; } public U Get&lt;U&gt;(string PropertyName) { // Search through the type's properties for one with this name // Properties are things with get/set accessors PropertyInfo property = typeof(T).GetProperty(PropertyName); if (property == null) { // if we couldn't find a property, look for a field. // Fields are just member variables, but you can only // manipulate public ones like this. FieldInfo field = typeof(T).GetField(PropertyName); if (field == null) throw new Exception("Couldn't find a property/field named " + PropertyName); return (U)field.GetValue(Instance); } return (U)property.GetValue(Instance, null); } public void Set&lt;U&gt;(string PropertyName, U value) { // Search through the type's properties for one with this name PropertyInfo property = typeof(T).GetProperty(PropertyName); if (property == null) { // if we couldn't find a property, look for a field. FieldInfo field = typeof(T).GetField(PropertyName); if (field == null) throw new Exception("Couldn't find a property/field named " + PropertyName); field.SetValue(Instance, value); return; } property.SetValue(Instance, value, null); } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload