2010-01-18 50 views
5

嗨,夥計們我有一個非常簡單的類叫做person。WCF讀取DataMember名稱屬性

public class Person{ 
    [DataMember(Name="MyName")] 
    public string Name { get;set;} 
} 

如果我嘗試序列化或反序列化,一切都很好。在XML中,我可以看到一個名爲「MyName」的標籤,並在VS Intellisense中看到名爲Name的屬性。 我現在需要的是從對象訪問屬性的序列化名稱。例如,我可以做這個object.GetType()。GetProperty(「Name」);但如果我嘗試做這個object.GetType()。GetProperty(「我的名字」)反射說,該屬性不存在。我如何閱讀財產的序列化名稱?有沒有辦法?

+0

你想從服務端或客戶端做到這一點? – 2010-01-18 19:46:12

+0

從客戶端,DataContractSerializer無法讀取屬性的屬性。我也試着用XDocument和Linq。有什麼建議麼? – Raffaeu 2010-01-18 19:53:56

回答

3

看來,唯一的辦法是訪問,使用反射,這樣的財產屬性:

var att = myProperty.GetType().GetAttributes(); 
var attribute = property.GetCustomAttributes(false)[0] as DataMemberAttribute; 
Console.WriteLine(attribute.Name); 

這部作品既,客戶端和服務器,而不需要序列化和反序列化目的。

+1

一些空的檢查可能是有序的,你的答案只假設一個屬性,試着檢查像這樣:'var attribute =(DataMemberAttribute)propertyInfo.GetCustomAttributes(typeof(DataMemberAttribute),false).FirstOrDefault(); \t \t \t \t如果(屬性!= NULL) \t \t \t \t \t名= attribute.Name;' – Myster 2012-04-23 04:24:37