2017-08-16 204 views
-1

我有一个像下面的模型类,不能类型为MyModel隐式转换为System.Collections.Generic.List <T>

public class MyModel 
{ 
    [SQLite.PrimaryKey] 
    public int Id { get; set; } 
    public string Name { get; set; } 
    public string Status { get; set; } 
} 

和接口类,其中在我是谁的返回类型的方法是类型为MyModel类方法是像下面,

public interface IService 
{ 
    List<MyModel> IGetEmployeeDetails(); 
} 

和上述界面已经在如下我的服务类得到执行,

public List<MyModel> IGetEmployeeDetails() 
{ 
    return _connection.Table<MyModel>().ToList(); 
} 

一切工作正常,我通过上面的实现,但是当我试图改变我的接口方法一般返回类型,我面临的问题与我的接口方法的返回类型,像下面

List<MyModel> IGetEmployeeDetails();List<T> IGetEmployeeDetails<T>();我“M越来越

无法隐式转换类型MyModelSystem.Collections.Generic.List<T>

基本上,我想我的接口方法的返回类型通用的,但我不知道如何在我的服务类中从MyModel到泛型类型的类型结果。

FYI我已经试过以下的情况下,

  • return _connection.Table<MyModel>().ToList<T>();
  • return (List<T>)_connection.Table<MyModel>().ToList(); &等

任何帮助提前被大加赞赏。

回答

0

基本上,我想我的接口方法的返回类型通用的,但 我不知道如何从 MyModel强制转换在我的服务类的结果,泛型类型。

您正在寻找的是类的级别泛型,而不是函数级别,正如您尝试的那样。

如果函数是泛型函数,那么调用者指定一个T,函数必须处理它。在你的情况下,你需要不同的IService实现,每个都能够返回不同的集合。所以:

public interface IService<T> 
{ 
    List<T> GetEmployeeDetails(); 
} 

和派生:

public class DerivedService : IService<MyModel> 
{ 
    public List<MyModel> GetEmployeeDetails() 
    { 
     return _connection.Table<MyModel>().ToList(); 
    } 
} 
+0

非常感谢@Gilad绿色,这工作就像一个魅力:) –

+0

@Anamikaunknown - 欢迎您:) –

相关问题