c# - 在 C# 中使用抽象类

标签 c# .net oop class

我有一个抽象类,其他类正在继承它。

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/

相关文章:

OOP 是否所有属性都有 getter 和 setter

c# - Nhibernate 事务 :Avoiding Nhibernate dependency in the service layer

.net - COM 互操作 : indexed property signature issues

PHP 类 - 使用普通变量而不是属性更可取吗?

c# - 了解 C# 中 Timer 控件的工作原理

.net - 如何确定当前应用程序是否为 ASP.NET Web 应用程序

java - 如何在 Java 中 DRY 这些代码块?

C# - backgroundworker 等待创建文件

c# - 实际引用而不是复制 PtrToStructure?

c# - 使用 C# 用 LINQ 任意匹配项填充变量