我有一个抽象类,其他类正在继承它。
public abstract class GenericAccess<TEntity>
{
public static IList<TEntity> GetObjectListFromArray(int[] IDs)
{
//Your help need is here.
}
}
public class Doors : GenericAccess<DoorEntity>
{
}
public class DoorEntity
{
public int Id { get; set; }
public string Name { get; set; }
}
我需要创建一个通用方法,例如,当我可以的时候
IList<DoorEntity> Doors.GetObjectListFromArray(int[] {1,2,3,4,5});
它将返回一个 IList,其中包含所有对象,属性 Id 加载了传递的值。在上面的示例中,它将返回一个列表,其中包含 5 个项目,其中加载了 DoorEntity 的 Id。
最佳答案
使用接口(interface)或基类...
带接口(interface):
public abstract class GenericAccess<TEntity> where TEntity : IEntity, new()
{
public static IList<TEntity> GetObjectListFromArray(int[] IDs)
{
return IDs.Select(id => new TEntity { Id = id }).ToList();
}
}
public class Doors : GenericAccess<DoorEntity>
{
}
public class DoorEntity : IEntity
{
public int Id { get; set; }
public string Name { get; set; }
}
public interface IEntity
{
int Id { get; set; }
string Name { get; set; }
}
有一个基类:
public abstract class GenericAccess<TEntity> where TEntity : Entity, new()
{
public static IList<TEntity> GetObjectListFromArray(int[] IDs)
{
return IDs.Select(id => new TEntity { Id = id }).ToList();
}
}
public class Doors : GenericAccess<DoorEntity>
{
}
public class DoorEntity : Entity
{
}
public abstract class Entity
{
public int Id { get; set; }
public string Name { get; set; }
}
关于c# - 在 C# 中使用抽象类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6206277/