首页 > 解决方案 > 如何传递 ObservableCollection 的类型

问题描述

我有一个类似于这个的功能,我无法编辑它:

internal object DoSomething(Type type, object obj)

我需要将类型作为 ObservableCollection 的类型传递,但 T 在设计时是未知的。

这还不够:

Type t = typeof(ObservableCollection<>);

我该如何解决?

编辑

使用 LiteDb 时,您可以将 POCO 类属性映射到 LiteDb 对象。默认情况下,ObservableCollection 返回一个数组。我需要通过 ObservableCollectio 更改此默认行为并取回 BsonDocument

此代码有效:

BsonMapper.Global.RegisterType<ObservableCollection<Phone>>
              (serialize: (ObservableCollection) => OCToDoc(Client.Phones),
              deserialize: (BsonDocument) => new ObservableCollection<Phone>()
              );


    public BsonDocument OCToDoc<T>(ObservableCollection<T> oc)
    {           

        BsonDocument doc = new BsonDocument();
        Type t = typeof(T);
        BsonDocument item = new BsonDocument();
        doc.Add(t.Name, item);

        foreach (PropertyInfo pi in t.GetProperties())
        {
            string key = pi.Name;
            item.Add(key, new BsonValue());
        }

        return doc;
    }

LiteDb.dll 中的 RegisterType 是:

public void RegisterType<T>(Func<T, BsonValue> serialize, Func<BsonValue, T> deserialize);
public void RegisterType(Type type, Func<object, BsonValue> serialize, Func<BsonValue, object> deserialize);

我需要为任何类型的 ObservableCollection 进行通用映射。这意味着

ObservableCollection<Phone> 

一定是

ObservableCollection<T> 

其中 T 在运行时未知。那么,如何在 RegisterType<...> 和 OCToDoc(...) 中传递 ObservableCollection

标签: c#litedb

解决方案


您需要调用该类型的方法以将其绑定到泛型参数:

typeof(ObservableCollection<>).MakeGenericType(someType);

推荐阅读