假设我在类或方法中有一个泛型成员,所以:
public class Foo<T>
{
public List<T> Bar { get; set; }
public void Baz()
{
// get type of T
}
}
Run Code Online (Sandbox Code Playgroud)
当我实例化类时,T变为MyTypeObject1,所以类具有通用列表属性:List<MyTypeObject1>.这同样适用于非泛型类中的泛型方法:
public class Foo
{
public void Bar<T>()
{
var baz = new List<T>();
// get type of T
}
}
Run Code Online (Sandbox Code Playgroud)
我想知道,我的类列表包含什么类型的对象.所以调用的list属性Bar或局部变量baz包含什么类型的T?
我做不到Bar[0].GetType(),因为列表可能包含零元素.我该怎么做?
我正在做一个反思项目,现在我被卡住了.如果我有一个可以容纳List的"myclass"对象,那么如果属性myclass.SomList为空,是否有人知道如何获取下面代码中的类型?
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 …Run Code Online (Sandbox Code Playgroud)