Reputation: 1946
I am writing a web service to expose certain pieces of data to one of our third party applications. Their team requires a generic way to retrieve values of fields in our system. I have written a class where the only public members of the class are the values they need. What I would like to do is have them pass an enumerated string that is the name of the member they want to retrieve and if it is a valid name of a public member, return the value of that member. I was messing around with some of the reflection methods in .net but can't quite get the behavior I am looking for. I am trying to write something to recreate the functionality of this pseudo code:
public Object webserviceMethodToReturnValue(Guid guidOfInternalObject, String nameOfProperty)
{
internalObject obj = new internalObject(guid); //my internal company object, which contains all the public members the external company will need
Object returnObject = obj.{nameOfProperty}; //where name of property is evaluated as the name of the member of the internalOject
return returnObject; //returning an object that could be casted appropriately by the caller
}
So that you could call the service like:
String companyName = (String)webserviceMethodToReturnValue(guid, "companyName");
Upvotes: 0
Views: 249
Reputation: 3972
Yep! you would do this: typeof(InternalObject).GetProperty(nameOfProperty).GetValue(obj,null)
Upvotes: 0
Reputation: 887877
You need to call the GetProperty
method, like this:
PropertyInfo property = typeof(InternalObject).GetProperty(nameOfProperty);
return property.GetValue(obj, null);
Beware that it won't be very fast.
To make it faster, you could use expression trees in .Net 3.5 to create statically-typed methods at runtime that return the values.
Upvotes: 4