mardi 1 décembre 2015

How to return lambda of unknown type from function in .NET 3.5?

I'm trying to make a simple IoC framework.

I want to make a mapping function from T to instance of Tas a part of it - get<T>.

get<T>()=new Mock<T>() if T is NOT a Func
get<T>()=()=>new Mock<R>() if T is a Func<R>
get<T>()=(P1)=>new Mock<R>(P1) if T is a Func<P1,R>
get<T>()=(P1,P2)=>new Mock<R>(P1,P2) if T is a Func<P1,P2,R>
//etc.

I wrote the following code:

public override Maybe<T> get<T>()
{
    return (T)get_default_unit_testing_definition<T>();
}
Object get_default_unit_testing_definition<T>() where T :class
{
    Type type = typeof(T);
    if (!type.IsGenericType)
        return new Mock<T>();
    Type generic = type.GetGenericTypeDefinition();
    Type return_type = type.GetGenericArguments().Last();
    Type mock_type_definition = typeof(Mock<>);
    var concrete_mock_definition = mock_type_definition.MakeGenericType(return_type);
    if (generic == typeof(Func<>))
    {
        return () => Activator.CreateInstance(concrete_mock_definition);
    }
    else if (generic == typeof(Func<,>))
    {
        return p1 => Activator.CreateInstance(concrete_mock_definition, p1);
    }
    //...
    return new Mock<T>();
}

but the compiler responds me with: cannot convert lambda expression to type "object" because it's not a delegate type

It's .NET 3.5, so I have no dynamic keyword.

Assigning lambda to var is also impossible.

How do I return these lambdas?





Aucun commentaire:

Enregistrer un commentaire