मैं एक प्रतिबिंब परियोजना पर काम कर रहा हूं, और अब मैं अटक गया हूं। यदि मेरे पास "myclass" का कोई ऑब्जेक्ट है जो सूची रख सकता है, तो क्या कोई यह जानता है कि संपत्ति myclass.SomList खाली है, तो नीचे दिए गए कोड में टाइप कैसे प्राप्त करें?सी # सामान्य सूची <T> टी के प्रकार कैसे प्राप्त करें?
List<myclass> myList = dataGenerator.getMyClasses();
lbxObjects.ItemsSource = myList;
lbxObjects.SelectionChanged += lbxObjects_SelectionChanged;
private void lbxObjects_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
Reflect();
}
Private void Reflect()
{
foreach (PropertyInfo pi in lbxObjects.SelectedItem.GetType().GetProperties())
{
switch (pi.PropertyType.Name.ToLower())
{
case "list`1":
{
// This works if the List<T> contains one or more elements.
Type tTemp = GetGenericType(pi.GetValue(lbxObjects.SelectedItem, null));
// but how is it possible to get the Type if the value is null?
// I need to be able to create a new object of the type the generic list expect.
// Type type = pi.getType?? // how to get the Type of the class inside List<T>?
break;
}
}
}
}
private Type GetGenericType(object obj)
{
if (obj != null)
{
Type t = obj.GetType();
if (t.IsGenericType)
{
Type[] at = t.GetGenericArguments();
t = at.First<Type>();
} return t;
}
else
{
return null;
}
}
यह प्रकार itemtype = interfaceType.GetGenericArguments() नहीं होना चाहिए [0]; – Muxa
Amusingly, दूसरा उदाहरण 'IList' कहता है, के साथ विफल रहता है। नीचे ठीक करें http://stackoverflow.com/a/13608408/284795 –
मुझे पता है कि उत्तर बहुत पुराना है, लेकिन मैं निम्नलिखित को समझने की कोशिश करता हूं: 'GetGenericArguments() [0];' 0 क्यों है? क्या टाइप [] में केवल हमेशा एक आइटम है? – Ismoh