简体   繁体   中英

C# Return generic class from method

Here is my code below, with unimportant parts redacted:

public class Response<T>
{
    //...
}

public class Summary
{
    //...
}

public class Db : IDb
{
    public Response<Summary> Generate()
    {
        //...
        return new Response<Summary>
        {
            //...
        };
    }

    public Response<Summary> Execute<Summary>()
    {
        return Generate();
    }
}

I get an error that says: Cannot implicitly convert type Response<Service.Models.Summary> to Response<Summary>.

Am I using generics wrong? Basically, I am expecting to see a Response model when I call the method Generate(), and in this instance T is the Summary class.


The interface I'm implementing is this:

public interface IDb
{
    Response<T> Execute<T>();
}

Your method public Response<Summary> Execute<Summary>() has a generic parameter of Summary that is overriding the class definition of Summary . The return type of Response<Summary> in Execute<Summary>() is a different type than the return in Generate() .

It seems likely that you code should be:

public Response<Summary> Generate()
{
    //...
    return new Response<Summary>
    {
        //...
    };
}

public Response<Summary> Execute()
{
    return Generate();
}

Given the addition of your interface IDb then the above answer doesn't work.

You must implement Execute as public Response<T> Execute<T>() and that means that the return type Response<T> is not the same as Response<Summary> at compile-time . So the error is correct.

You basically now have a design flaw.

It's likely that you need to make this change:

public class Db : IDb<Summary>
{
    public Response<Summary> Generate()
    {
        //...
        return new Response<Summary>
        {
            //...
        };
    }

    public Response<Summary> Execute()
    {
        return Generate();
    }
}

public interface IDb<T>
{
    Response<T> Execute();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM