Search code examples
c#.netportable-class-library

PCL - Can't convert from Func<IThing<T>> to Func<Object> for some targets


I currently have a PCL library that incorporates a factory something like this (names changed to protect the innocent):

public abstract class ThingFactory : IThingFactory
{
    private readonly Dictionary<string, Func<object>> _registrations = new Dictionary<string, Func<object>>();

    protected void Register<T>(string name, Func<IThing<T>> resolver) where T : IModel<T>
    {
        _registrations.Add(name, resolver);
    }

    // ... Resolve casts invocation back to IThing<T>.
}

The library builds and tests perfectly for .NET 4.0 above and SL 5.

Any other targets (SL 4, Windows phone etc) cause a compilation failure with the conversion message:

Error 2 Argument 2: cannot convert from 'System.Func<IThing<T>>' to 'System.Func<object>'

Any suggestions?


Solution

  • You can fix it using this code:

        protected void Register<T>(string name, Func<IThing<T>> resolver) where T : IModel<T>
        {
            Func<object> wrapper =  () => resolver();
            _registrations.Add(name, wrapper);
        }
    

    I guess the reason is that pre .NET 4.0 there is no variance support for func/action