的PropertyDescriptor與我有以下代碼:檢索嵌套對象
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
object o;
Person p = new Person { FirstName = "John", Surname = "Henry" };
Citizen c = new Citizen { Country = "Canada", ResidentName = p };
SportsFan sf = new SportsFan { Sport = "Hockey", Fan = c };
Discoverer<SportsFan>.SimpleExample("Sport", "Hockey",out o);
Discoverer<SportsFan>.NestedProperyExample("Fan.Citizen.FirstName", "John",out o);
}
private class Person
{
public string FirstName
{
get; set;
}
public string Surname
{
get; set;
}
}
private class Citizen
{
public Person ResidentName
{
get; set;
}
public string Country
{
get; set;
}
}
private class SportsFan
{
public string Sport
{
get; set;
}
public Citizen Fan
{
get; set;
}
}
private class Discoverer<T>
{
public static void SimpleExample(string propName, string objResultToString,out Object obj)
{
PropertyDescriptor propDesc;
propDesc = TypeDescriptor.GetProperties(typeof(T))[propName];
TypeConverter converter = TypeDescriptor.GetConverter(propDesc.PropertyType);
obj = converter.ConvertFromString(objResultToString);
}
public static void NestedProperyExample(string propName, string objResultToString, out Object obj)
{
PropertyDescriptor propDesc = null;
obj = null;
string[] nestedProperties = propName.Split(new char[] { '.' }, StringSplitOptions.RemoveEmptyEntries);
propDesc = TypeDescriptor.GetProperties("Form1." + nestedProperties[0])[nestedProperties[1]];
for (int i = 1; i < nestedProperties.Length - 1; i++)
{
if (propDesc != null)
propDesc = TypeDescriptor.GetProperties(propDesc.GetType())[nestedProperties[i + 1]];
}
if (propDesc != null)
{
TypeConverter converter = TypeDescriptor.GetConverter(propDesc.PropertyType);
obj = converter.ConvertFromString(objResultToString);
}
}
}
}
代碼工作的simpleExample
。在NestedPropertyExample
上,第一次轉讓給PropDesc
返回null
。當我檢查TypeDescriptor.GetProperties("Form1." + nestedProperties[0])
時,它返回一個項目的PropertyDescriptorCollection
,這是長度。
爲什麼我不會返回更多PropertyDesriptor
項目?我正在以正確的方式來解決這個問題嗎?
謝謝你,比爾ñ