将对象转换为 ObservableCollection<object>

Casting an object as an ObservableCollection<object>

我正在尝试编写一个方法来获取 viewModel 中的所有 ObservableCollections 并将每个对象转换为 ObservableCollection<object>。使用反射我已经能够将每个 ObservableCollection<T> 作为一个对象,但是我在将这个对象转换为 ObservableCollection<object> 时遇到了困难。到目前为止,这是我的代码:

var props = viewModel.GetType().GetProperties();

Type t = viewModel.GetType();

foreach (var prop in props)
{
    if (prop.PropertyType.Name == "ObservableCollection`1")
    {
        Type type = prop.PropertyType;
        var property = (t.GetProperty(prop.Name)).GetValue(viewModel);

        // cast property as an ObservableCollection<object>
    }
}

有人知道我应该如何进行吗?

这个问题的答案在这里:

但是要为你的情况说清楚:

if (prop.PropertyType.Name == "ObservableCollection`1")
{
    Type type = prop.PropertyType;
    var property = (t.GetProperty(prop.Name)).GetValue(viewModel);

    // cast property as an ObservableCollection<object>
    var col = new ObservalbeCollection<object>(property);
    // if the example above fails you need to cast the property
    // from 'object' to an ObservableCollection<T> and then execute the code above
    // to make it clear:
    var mecol = new ObservableCollection<object>();
    ICollection obscol = (ICollection)property;
    for(int i = 0; i < obscol.Count; i++)
    {
        mecol.Add((object)obscol[i]);
    }    
    // the example above can throw some exceptions but it should work in most cases
}

您可以使用 Cast<T>() 扩展方法,但不要忘记,使用此方法(如下)将创建一个新实例,因此原始事件不起作用。如果您仍想接收事件,则应为其创建一个包装器。

var prop = viewModel.GetType("ObservableCollection`1");

var type = prop.PropertyType;
var propertyValue = (t.GetProperty(prop.Name)).GetValue(viewModel);

// cast property as an ObservableCollection<object>
var myCollection = new ObservableCollection<object>(
                   ((ICollection)propertyValue).Cast<object>());

}

将类型名称与字符串进行比较是个坏主意。为了断言它是一个 ObservableCollection,您可以使用以下内容:

if (prop.PropertyType.IsGenericType && 
    prop.PropertyType.GetGenericTypeDefinition() == typeof(ObservableCollection<>))

可以这样提取和转换值:

foreach (var prop in viewModel.GetType().GetProperties())
{    
    if (prop.PropertyType.IsGenericType && 
        prop.PropertyType.GetGenericTypeDefinition() == typeof(ObservableCollection<>))
    {
        var values = (IEnumerable)prop.GetValue(viewModel);

        // cast property as an ObservableCollection<object>
        var collection = new ObservableCollection<object>(values.OfType<object>());
    }
}

如果你想将它们合并为一个集合,你可以这样做:

var values = viewModel.GetType().GetProperties()
    .Where(p => p.PropertyType.IsGenericType)
    .Where(p => p.PropertyType.GetGenericTypeDefinition() == typeof(ObservableCollection<>))
    .Select(p => (IEnumerable)p.GetValue(viewModel))
    .SelectMany(e => e.OfType<object>());
var collection = new ObservableCollection<object>(values);