I have a working setup which is not strongly typed and relies on reflection.
I have a class, say
class Person{
public string FirstName {get ; set;}
public string LastName {get; set;}
public int Age {get; set;}
...
// some more public properties
}
and
class CellInfo {
public string Title {get; set;}
public string FormatString {get; set;}
}
and I have a dictionary like this
Dictionary<string, CellInfo> fields = new Dictionary<string, CellInfo>();
fields.Add("FirstName", new CellInfo {Title = "First Name", FormatString = "Foo"});
fields.Add("LastName", new CellInfo {Title = "Last Name", FormatString = "Bar"});
It's a simple dictionary with property Names and some info about them. I pass the dictionary to another module that processes Person instances and I do
Dictionary<string, CellInfo> fields = SomeMethodToGetDictionary();
foreach(Person p in someCollection)
{
foreach(var field in fields)
{
object cellValue = type(Person).GetProperty(field.Key).GetValue(p, null);
// use cellValue and info on field from field.Value somewhere.
...
}
}
This method of passing the string for field name and using reflection works, but I was wondering if there is a strongly-typed method of doing this.
What I had in mind was having a property that stored a linq expression, something like this
fields.Add("FirstName", new CellInfo
{
Title = "First Name",
FormatString = "Foo",
EvalExpression = p => p.FirstName
});
and during usage, somehow use the EvalExpression
on a person object and get the property value. I have no clue where to begin or what the syntax would be like to have a property like this that's evaluateable. I'm new to function delegates and expression trees that I don't even know the right keywords to search for. Hope my description is clear; if not, let me know and I'll details as necessary.
Any assistance would much appreciated.
Func<Person, string>
is a shorthand for the delegate you have and someone didn't realize that and gave you a downvote. – Aras