Reputation: 302
This won't make a lot of sense so apologies in advance, I'm not a C# developer but have been given some code to look at.
I need to pass a model object in to a function, however I looping through and so will need to build the name dynamically. So lets assume I would normally reference it like so.
model.employee.title
model.employee.forename
How can I reference it using a string for the last part.
I'm using a foreach to loop through the various parts which is fine, but I then need to pass the object in to a function call. I have the name of the last part as a literal string ("title","forname") but I'm not sure how I pass that in.
So effectively what I need is to use something like
model.employee."title"
or
model.employee.varContainingTheName
I know these won't work, but have no idea how to proceed.
Upvotes: 3
Views: 101
Reputation: 6301
If you develop the model.employee class and use it like that, you should consider using dictionary for fileds.
class employee
{
public Dictionary<string, object> properties = new Dictionary<string,object>();
public employee()
{
properties.Add("time", DateTime.Now);
properties.Add("name", "Bill Gates");
}
}
and then use it like this:
Employee employee = new Employee();
employee.properties["time"];
this code will be faster and easier to read.
Upvotes: 1
Reputation: 1062975
Basically, if you have a string of the member name, you're talking about reflection. The reflection API differs between fields and properties, so you'd need to know which it is, for example (where obj
is model.employee
, and name
is the name of the member you want to access):
object value = obj.GetType().GetField(name).GetValue(obj);
vs:
object value = obj.GetType().GetProperty(name).GetValue(obj, null);
Alternatively, use an API like FastMember (which incidentally is much faster than raw reflection - it uses lots of voodoo):
var wrapper = ObjectAccessor.Create(obj);
object value = wrapper[name];
Upvotes: 3