Quantcast
Channel: Best practice instantiating generic delegates and accessing property getters - Stack Overflow
Viewing all articles
Browse latest Browse all 4

Best practice instantiating generic delegates and accessing property getters

$
0
0

I want to create delegates to access properties of different objects without knowing them in advance.

I have the following definitions

public delegate T MyMethod<K, T>(K data);public static MyMethod<K, T> CreatePropertyGetter<K, T>(PropertyInfo property){          MethodInfo mi = property.DeclaringType.GetMethod("get_"+ property.Name);        return (MyMethod<K, T>)Delegate.CreateDelegate(typeof(MyMethod<K, T>), mi);}

where T can be decimal, string, datetime or int

I have some initializing code that will create MyMethod delegates, based on the reflected properties of my object as follows:

foreach (PropertyInfo property in entityType.GetProperties()){                   switch (property.PropertyType.Name)    {        case "System.Decimal":            return CreatePropertyGetter<T, decimal>(property);        case "System.DateTime":            return CreatePropertyGetter<T, DateTime>(property);        case "System.String":            return CreatePropertyGetter<T, DateTime>(property);    }}

Is there a better way to

  1. create property getters?
  2. enumerate through the supported property types hard-coded as strings?

EDIT:

My concern is performance, since these delegates will be called frequently (ticking scenario), so any casting will slow it down. While a more elegant solution is desirable, performance is still my main concern

I posted the same question on Code Review here, so i will mark this as solved considering the response there


Viewing all articles
Browse latest Browse all 4

Latest Images

Trending Articles





Latest Images