以接口为返回类型的方法,拒绝返回具有实现的类

时间:2021-03-24 10:34:12

标签: c# interface casting return implementation

以下方法设置为返回实现 IResultSchema 的结果。 我这样做了,但 VS 抱怨它无法将实现的类(ResultSchema 和 EmployeeSchema)转换为接口。它告诉我进行转换,但转换在运行时失败。我不想更改方法的返回类型,因为方法所属的类、实现和定义方法的接口。那会破坏使用接口的意义。 “apiResponse.Response”中的数据看起来很完美。 在该方法的正上方,在同一个类中,我有另一个方法返回“IEnumerable”并且工作正常。

方法:

public async Task<IResultSchema<IEmployeeSchema>> GetEmployees(int customerId, string token, int take, int skip, string direction, string column, string query)
        {
            if (token.IsTokenValid())
            {
                string endpoint;

                //Stuff for setting the endpoint string here

                var apiResponse = await CallApi<int, ResultSchema<EmployeeSchema>>(Enums.Method.Get, endpoint, token, default(int));

                if (apiResponse.HasError) return null;

                return apiResponse.Response;
            }

            return null;
        }

IResultSchema 和 IEmployeeSchema:

public interface IResultSchema<T>
    {
        IEnumerable<T> Records { get; set; }
        int Total { get; set; }
    }

 public interface IEmployeeSchema
    {
        IEnumerable<IApplicationSchema> Applications { get; set; }
        //Rest of the props here
    }

IResultSchema 和 IEmployeeSchema 的实现:

public class ResultSchema<T> : IResultSchema<T>
    {
        public ResultSchema()
        {
            Records = new List<T>();
        }

        public IEnumerable<T> Records { get; set; }

        public int Total { get; set; }
    }

public sealed class EmployeeSchema : IEmployeeSchema
    {
        public EmployeeSchema()
        {
            Applications = new List<ApplicationSchema>();
        }
        
        public IEnumerable<IApplicationSchema> Applications { get; set; }
        //Rest of the props here
    }


0 个答案:

没有答案
相关问题