2010-01-12 96 views
0

我正在编写一个Web服务以将某些数据片段暴露给我们的第三方应用程序之一。他们的团队需要一种通用的方式来检索我们系统中的字段值。我写了一门课,只有班上的公共成员是他们需要的价值观。我想要做的是让他们传递一个枚举字符串,它是要检索的成员的名称,如果它是公共成员的有效名称,则返回该成员的值。我在.net中使用了一些反射方法,但无法完全达到我所期望的行为。我想写的东西重新的这种伪代码的功能:使用变量值作为C#中返回值的变量名称

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 
} 

所以,你可以调用类的服务:

String companyName = (String)webserviceMethodToReturnValue(guid, "companyName"); 

回答

4

你需要调用GetProperty方法,像这样:

PropertyInfo property = typeof(InternalObject).GetProperty(nameOfProperty); 
return property.GetValue(obj, null); 

小心,它不会是非常快的。

为了使其更快,你可以使用表达式树的。Net 3.5在运行时创建静态类型的方法,返回的值。

+0

没错。除了需要GetValue以外,我已经能够查看所有内容。谢谢。 – kscott 2010-01-12 21:01:26

0

是的!你可以这样做:typeof(InternalObject).GetProperty(nameOfProperty).GetValue(obj,null)