使用泛型和'new'修饰符隐藏父级成员时,C#继承会出现问题

时间:2019-01-17 03:50:29

标签: c# linq generics inheritance modifier

我正在尝试创建具有2个级别的类层次结构 其中第二级覆盖其中一个属性(例如ID)。

// Level 1
public class Level1 : IEntity
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }
}

// Level 2
public class Level2 : Level1
{
    // Override the 'Id' property in Level1
    // for the purpose of turning off auto-increment on Id.
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public new int Id { get; set; }
}

这是一个演示问题的自包含代码段。

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using Example;

public class Program
{
    public static void Main()
    {
        // Using concrete class, logic works correctly
        var tester = new Tester();

        Console.WriteLine("\n");

        // Using Generic, result is incorrect
        var testerGeneric = new TesterGeneric<Level2>();
    }
}

///////////////////////////////////////////////////////////////////////////

public class Tester
{
    public Tester()
    {
        Console.WriteLine("------ Tester Class ------");

        var listOfEntities = Level2.CreateDummyRecords();
        Console.WriteLine("List Count = " + listOfEntities.Count());        // Returns 6 (as expected)

        var groupedItems = listOfEntities.GroupBy(g => g.Id);
        Console.WriteLine("Grouped By Count = " + groupedItems.Count());    // Returns 3 (as expected)
    }
}

public class TesterGeneric<TEntity>
                where TEntity : class, IEntity, new()
{
    public TesterGeneric()
    {
        Console.WriteLine("------ TesterGeneric Class ------");

        var listOfEntities = (IEnumerable<TEntity>) Level2.CreateDummyRecords();
        Console.WriteLine("List Count = " + listOfEntities.Count());        // Returns 6 (as expected)

        var groupedItems = listOfEntities.GroupBy(g => g.Id);
        Console.WriteLine("Grouped By Count = " + groupedItems.Count());    // Returns 1 (should be 3)
    }
}

///////////////////////////////////////////////////////////////////////////

namespace Example
{
    public interface IEntity
    {
        int Id {get; set;}
    }

    // Level 1
    public class Level1 : IEntity
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int Id { get; set; }
    }

    // Level 2
    public class Level2 : Level1
    {
        // Override the 'Id' property in Level1
        // for the purpose of turning off auto-increment on Id.
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.None)]
        public new int Id { get; set; }

        public static IEnumerable<Level2> CreateDummyRecords()
        {
            var theList = new List<Level2>();

            theList.Add(new Level2() { Id=1 });

            theList.Add(new Level2() { Id=2 });
            theList.Add(new Level2() { Id=2 });

            theList.Add(new Level2() { Id=3 });
            theList.Add(new Level2() { Id=3 });
            theList.Add(new Level2() { Id=3 });

            return theList;
        }
    }
}

有两个“测试人员”课程

  • 测试器
  • TesterGeneric

测试器使用具体的类 Level2 ,并根据 Id 属性正确地将记录分组。

即输出:

  • 列表中有6个项目
  • 3组唯一ID

TesterGeneric 通过 TEntity 通用参数引用Level2 并且不正确通过 Id 属性对记录进行分组。

即输出:

  • 列表中有6个项目
  • 仅1个组(组Key为0)

问题: 这是怎么发生的?

2 个答案:

答案 0 :(得分:3)

我认为我们有一个非常简单的概念,用于new和override。在这里您可以轻松理解:

每当您覆盖子类的属性/方法时,如果将子对象强制转换为父类,则将具有子类的功能。

每当您将new关键字与子类的属性/方法一起使用,然后将子对象转换为父对象时,便会具有父类功能。

这是为您提供的简单代码示例:

  class Parent
{
    public virtual int ID { get { return 40; } }

}

class ChildWithNew: Parent
{
    public new int ID { get { return 50; } }
}

class ChildWithOverride : Parent
{
    public override int ID { get { return 60; } }
}

class Program
{
    static void Main(string[] args)
    {


        Console.WriteLine("---Child with Override Kyword");
        ChildWithOverride cildWithOverride = new ChildWithOverride();

        Console.WriteLine(cildWithOverride.ID);
        Console.WriteLine(((Parent)cildWithOverride).ID);

        Console.WriteLine("---Child with New Kyword");
        ChildWithNew childWithNew = new ChildWithNew();

        Console.WriteLine(childWithNew.ID);
        Console.WriteLine(((Parent)childWithNew).ID);

        Console.ReadLine();
    }


}

让我知道是否有帮助。

答案 1 :(得分:2)

您没有覆盖属性ID,现在只隐藏了属性。一旦您提供了虚拟的ID并覆盖了ID,该问题就会得到解决。