相关疑难解决方法(0)

如何从泛型类或方法的成员中获取T的类型?

假设我在类或方法中有一个泛型成员,所以:

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(),因为列表可能包含零元素.我该怎么做?

.net c# generics

647
推荐指数
11
解决办法
60万
查看次数

C#通用列表<T>如何获取T的类型?

我正在做一个反思项目,现在我被卡住了.如果我有一个可以容纳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)

c# reflection generic-list

110
推荐指数
4
解决办法
13万
查看次数

标签 统计

c# ×2

.net ×1

generic-list ×1

generics ×1

reflection ×1