Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
Question
Monday, December 3, 2018 8:14 PM
I am using this .Net reflection TypeBuilder class to generate a class instance at runtime.
I am using .Net reflections to create list of objects with dynamic set of properties since I am reading input from excel file which may have dynamic columns as per the business requirement. But I am doing lot of loops to get the GetType().GetProperty("")
which is reducing the performance. I am trying to delegate it dynamically for the PropertiesInfo[]
which I get from the GetType().GetProperties()
.
Below is a static getter and setter delegate for Property1 of the runtime class create
Action<MyClass, int> setter = (Action<MyClass, int>)Delegate.CreateDelegate(typeof(Action<MyClass, int>), null, typeof(MyClass).GetProperty("Property1").GetSetMethod());
I would like to make this dynamic for each property created of my class. I'm stuck and not sure whether I can use any Linq MemberExpression to achieve it.
Can anyone help me out? That would be great.
All replies (1)
Tuesday, December 4, 2018 7:28 AM
Hi Harihara Krishnan ,
Thank you for posting here.
For your question, I made the following code.
1. I got all the properties in the class through PropertyInfo and stored them in an array.
2. I use a foreach loop to iterate through the properties in the array, and a property creates a delegate.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace test1
{
public class MyClass
{
private string name;
public string Name
{
get
{
return name;
}
set
{
name = value;
}
}
public string ID
{
get
{
return id;
}
set
{
id = value;
}
}
private string id;
}
class Program
{
static void Main(string[] args)
{
Type t = typeof(MyClass);
PropertyInfo[] properties = t.GetProperties();
foreach (var item in properties)
{
Action<string> setter = (Action<string>)Delegate.CreateDelegate(typeof(Action<string>), null, typeof(MyClass).GetProperty(item.Name).GetSetMethod());
}
Console.ReadKey();
}
}
}
Best regards,
Jack J Jun.
MSDN Community Support
Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact [email protected].