mercredi 17 août 2016

C# - Returning an implementation when generic method type is an Interface

This is how I want to use it:

var fooStuff = _foo.DoBarStuff().GetFooStuff(id);

I'd like to return the implementation when DoBarStuff() is called so that I can call GetFooStuff(id) to get fooStuff.

public interface IFoo() : IBar
{
    FooStuff GetFooStuff(int id);
}

public class Foo
{
    public FooStuff GetFooStuff(int id)
    {
        // get fooStuff
        return fooStuff;
    }     
}

public interface IBar
{
      T DoBarStuff<T>();
}

public class Bar
{
    public T DoBarStuff<T>()
    {
        // do bar stuff
        return T; 
    }
}

The T is any interface and when 'return T;' is executed I need it's implementation returned. As it is now, I get this error under T on 'return T;' line.

T is a type, which is not valid in the given context. Type parameter name is not valid at this point.

Thanks!

Aucun commentaire:

Enregistrer un commentaire