2

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?


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

4

2 回答 2

5

That's because Func<T> was declared this way in .NET 3.5

public delegate TResult Func<TResult>()

Starting from .NET4 the declaration changed to

public delegate TResult Func<out TResult>()

Notice lack of out keyword in .NET 3.5 declaration. It makes the generic type covariant. You can read really good explanation about .NET covariance and contravariance support on MSDN.

于 2013-03-22T09:15:44.297 回答
2

您可以使用以下代码修复它:

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

我猜原因是 .NET 4.0 之前没有对 func/action 的差异支持

于 2013-03-22T09:08:54.347 回答