在转换为接口时,对象必须实现IConvertible(InvalidCastException)

art*_*ify 11 .net c# xml reflection casting

我正在尝试将某种类型的对象强制转换为它使用的接口Convert.ChangeType(),但是InvalidCastException由于该对象必须实现IConvertible,所以会抛出一个对象.

类型:

public IDocumentSet : IQueryable {}

public IDocumentSet<TDocument> : IDocumentSet, IQueryable<TDocument> {}

public XmlDocumentSet<TDocument> : IDocumentSet<TDocument> {}
Run Code Online (Sandbox Code Playgroud)

从发生错误的代码中摘录:

private readonly ConcurrentDictionary<Type, IDocumentSet> _openDocumentSets = new ConcurrentDictionary<Type, IDocumentSet>();

public void Commit()
{
    if (_isDisposed)
        throw new ObjectDisposedException(nameof(IDocumentStore));

    if (!_openDocumentSets.Any())
        return;

    foreach (var openDocumentSet in _openDocumentSets)
    {
        var documentType    = openDocumentSet.Key;
        var documentSet     = openDocumentSet.Value;

        var fileName        = GetDocumentSetFileName(documentType);
        var documentSetPath = Path.Combine(FolderPath, fileName);

        using (var stream = new FileStream(documentSetPath, FileMode.Create, FileAccess.Write))
        using (var writer = new StreamWriter(stream))
        {
            var documentSetType     = typeof (IDocumentSet<>).MakeGenericType(documentType);
            var writeMethod         = typeof (FileSystemDocumentStoreBase)
                                        .GetMethod(nameof(WriteDocumentSet), BindingFlags.Instance | BindingFlags.NonPublic)
                                        .MakeGenericMethod(documentSetType);
            var genericDocumentSet  = Convert.ChangeType(documentSet, documentSetType); <-------

            writeMethod.Invoke(this, new[] {writer, genericDocumentSet});
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

现在,我无法理解为什么会发生这种情况(因为XmlDocumentSet它不是值类型)和XmlDocumentSet<'1>实现IDocumentSet<'1>.我错过了什么吗?或者有更简单的方法来实现我正在做的事情?

Phi*_*ipH 3

IConvertible 接口旨在允许类将自身安全地转换为另一种类型。Convert.ChangeType 调用使用该接口将一种类型安全地转换为另一种类型。

如果您在编译时不知道类型,那么您将被迫尝试运行时强制转换。这是在一个非常类似的问题中讨论的:将变量转换为仅在运行时已知的类型?