xoofx / Tomlyn

Tomlyn is a TOML parser, validator and authoring library for .NET Framework and .NET Core
BSD 2-Clause "Simplified" License
424 stars 29 forks source link

InvalidCastException when ConvertToModel converts from a list to a non-list #68

Open GrantShotwell opened 1 year ago

GrantShotwell commented 1 year ago

Exception appears to be thrown in SyntaxToModelTransform.GetOrCreateSubObject(...), line 216.

The reason I am getting this exception is because I am trying to use wrappers for various types, and so implemented a ConvertToModel that creates the wrapper from the deserialized value. The error happens when the wrapped type is a list.

If it helps, the ConvertToModel function looks like this:

interface IWrapper<T> { T Value { get; } }
class StructValue<T> : IWrapper<T> where T : struct { /* ... */ }
class ReferenceValue<T> : IWrapper<T> where T : class { /* ... */ }
class ListValue<T> : IWrapper<IList<T>> { /* ... */ }
// ... and others

object? ConvertToModel(object deserialized, Type targetType) {
    // [return deserialized if deserialized.GetType() is already targetType]
    // [return null if targetType does not implement IWrapper]
    return CreateWrapper(deserialized, targetType);
}

This works for StructValue and ReferenceValue, just not ListValue because of the error.