C# 接收和使用任何类型的ObservableCollection<;T>;

C# 接收和使用任何类型的ObservableCollection<;T>;,c#,C#,我遇到了麻烦 我想接收任何集合,类型的ObservableCollection并使用它 例如,有这样一个类 public class Car{ int num; string str; } void showingProperties(ObservableCollection<T> coll) { foreach (T item in coll){ // showing item's property list } } 和可观测收集

我遇到了麻烦

我想接收任何集合,类型的ObservableCollection并使用它

例如,有这样一个类

public class Car{
    int num;
    string str;
}
void showingProperties(ObservableCollection<T> coll)
{
    foreach (T item in coll){
        // showing item's property list
    }
}
和可观测收集

ObservableCollection<Car> carOC = new ObservableCollection<Car>();
输出是

carOC has properties
num type int32
str type string
我真的不知道如何接收并使用它。。。
感谢您阅读。

事实上,您的问题与
可观察收集无关。您可以对任何通用集合执行相同的操作。只是为了澄清,
observateCollection
观察您的列表和项目,以便为您提供列表中变化的信息。它不会观察你的班级结构。在列表中这样做没有多大意义,因为您的t将在列表中存在好几次,但每个对象的信息都是相同的。因此,我建议您使用一种方法,为某个类型提供此类信息。请参见它基于类型而不是基于对象

public string ShowProperties<T>() : where T : class
{
   var props = typeof (T).GetProperties(BindingFlags.Instance | BindingFlags.Public);

    string typeInfo = typeof (T).FullName + Environment.NewLine;
    foreach (var prop in props)
    {
       typeInfo += prop.Name + " " + prop.PropertyType.FullName + Environment.NewLine;
    }

  return typeInfo;
}
公共字符串ShowProperties():其中T:class
{
var props=typeof(T).GetProperties(BindingFlags.Instance | BindingFlags.Public);
字符串typeInfo=typeof(T).FullName+Environment.NewLine;
foreach(道具中的var道具)
{
typeInfo+=prop.Name+“”+prop.PropertyType.FullName+Environment.NewLine;
}
返回typeInfo;
}
如果列表中有不同的项,由于继承关系,请在foreach循环中多次调用此项。但要小心,如果在循环中使用反射,反射速度会很慢。那就考虑缓存吧

public string ShowProperties<T>() : where T : class
{
   var props = typeof (T).GetProperties(BindingFlags.Instance | BindingFlags.Public);

    string typeInfo = typeof (T).FullName + Environment.NewLine;
    foreach (var prop in props)
    {
       typeInfo += prop.Name + " " + prop.PropertyType.FullName + Environment.NewLine;
    }

  return typeInfo;
}