Skip to main content
 首页 » 编程设计

c#之获取列表项的属性

2024年02月23日20落叶无声

假设我有一个类:

class SomeObject 
{ 
  public string Name{get;set;} 
  public string SomeProperty {get; set;} 
} 

我还有一个 SomeObjects 的列表:

List<SomeObject> list1 = new List<SomeObject>(); 
list1.Add(new SomeObject{ Name="Jhon", SomeProperty="baa bla bla"}); 
list1.Add(new SomeObject{ Name="Albert", SomeProperty="some description"}); 
list1.Add(new SomeObject{ Name="Tom", SomeProperty="some text"}); 

我想创建一个类,我可以在其中通过传递我想要填充的 ListView 和一个列表来填充 ListView。因此我的那个类的构造函数是这样的:

class MyListView 
{ 
    //Constructor 
    public MyListView(System.Windows.Controls.ListView listView, object list) 
    { 
          Lista = ((IEnumerable)list).Cast<object>().ToList(); // Cast the object list to List<objects> 
 
          var properties = Lista[0].GetType().GetProperties(); 
 
          foreach (var prop in properties) 
          { 
              // prop = Name then SomeProperty in this case 
              // create new column in listView 
              // etc 
          } 
 
    } 
} 

唯一的问题是,如果传递一个没有对象的列表,我不知道如何获取 SomeObject 的属性,因为我的构造函数假设列表不为空,因此通过获取第一个对象,它可以尝试查看属性。

所以我的问题是如何通过查看列表来获取 Name 和 SomeProperty 的属性。我想做类似的事情:

public MyListView(System.Windows.Controls.ListView listView, object list) 
{ 
   Lista = ((IEnumerable)list).Cast<object>().ToList(); // Cast the object list to List<objects> 
   properties = Lista.GetType().GetProperty("some property that refers to list items").GetType().GetProperties(); 

而不是试图从第一个对象中获取它们。我知道我可以修改构造函数并需要一个构造列表的对象并从该对象获取属性,但如果我不必传递那个额外的参数就更好了。

请您参考如下方法:

如果您假设 list 将是“某物”的 IEnumerable,为什么不继续使用类型参数来指定它.然后即使列表恰好为 null 或空也可以获取类型:

public class MyListView<T>{ 
    //Constructor 
    public MyListView(System.Windows.Controls.ListView listView, IEnumerable<T> list) 
    { 
          var properties = typeof(T).GetProperties(); 
 
          foreach (var prop in properties) 
          { 
              // prop = Name then SomeProperty in this case 
              // create new column in listView 
              // etc 
          } 
    } 
} 
 
// Example usage: Inferred type parameter  
List<SomeObject> list = null; 
var yourListView = new MyListView(listView1, list); 
 
// Example usage: Explicitly specify the type parameter if it can't be inferred 
var yourListView = new MyListView<SomeObject>(listView1, null);