Skip to main content
 首页 » 编程设计

c#之在泛型函数中使用基础对象作为参数

2024年02月24日15开发

我正在尝试使用泛型 (C#/3.5) 实现辅助方法 我有一个很好的类结构,基类如下:

public class SomeNiceObject : ObjectBase 
{ 
  public string Field1{ get; set; } 
} 
 
public class CollectionBase<ObjectBase>() 
{ 
  public bool ReadAllFromDatabase(); 
} 
 
public class SomeNiceObjectCollection : CollectionBase<SomeNiceObject> 
{ 
 
} 

我希望使用像这样的通用方法来检索集合:

    public class DAL 
    { 
 
     public SomeNiceObjectCollection Read() 
     { 
      return ReadFromDB<SomeNiceObjectCollection>(); 
     } 
 
     T ReadFromDB<T>() where T : CollectionBase<ObjectBase>, new() 
     { 
      T col = new T(); 
      col.ReadAllFromDatabase(); 
      return col;           
     } 
   } 

这不会构建,用

Error   66  The type 'SomeNiceObjectCollection' cannot be used as type parameter 'T' in the generic type or method 'ReadFromDB<T>'.   There is no implicit reference conversion from 'SomeNiceObjectCollection' to 'CollectionBase<ObjectBase>'. 

SomeNiceObjectCollection 对象是一个 CollectionBase,确切地说是一个 CollectionBase。那么我怎样才能让它发挥作用呢?

请您参考如下方法:

C# 不支持列表类型之间的转换(协变)。

支持此模式的最佳做法是为 ReadAllFromDatabase 方法引入一个接口(interface),这样您就不会依赖于通用集合:

public class SomeNiceObject : ObjectBase 
{ 
  public string Field1{ get; set; } 
} 
 
public interface IFromDatabase 
{ 
  bool ReadAllFromDatabase(); 
} 
 
public class CollectionBase<ObjectBase>() : IFromDatabase 
{ 
  public bool ReadAllFromDatabase(); 
} 
 
public class SomeNiceObjectCollection : CollectionBase<SomeNiceObject> 
{ 
 
} 
 
public class DAL 
{ 
 
 public SomeNiceObjectCollection Read() 
 { 
  return ReadFromDB<SomeNiceObjectCollection>(); 
 } 
 
 T ReadFromDB<T>() where T : IFromDatabase, new() 
 { 
  T col = new T(); 
  col.ReadAllFromDatabase(); 
  return col;           
 } 
}