2010-01-12 99 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)