【问题标题】:Extending inherited properties c#扩展继承的属性 c#
【发布时间】:2018-08-28 09:53:58
【问题描述】:

我有一个继承自基类的类

还有两个类具有这些原始类的列表作为属性

我认为这两个新类应该具有继承性,但似乎无法正常工作。

public class Attribute
{
    public string Name { get; set; }
    public string ShortName { get; set; }
    public bool Standard { get; set; }
}

public class BaseAttribute : Attribute
{
    public int Value { get; set; }
}

public class Profile
{
    public List<Attribute> AttributeList = new List<Attribute>
    {
        new Attribute {Name = "Hands", ShortName = "HA", Standard = true},
        new Attribute {Name = "Arms", ShortName = "AR", Standard = true},
    };
}

public class BaseProfile: Profile
{
    public List<BaseAttribute> AttributeList
    { get; set; }
}

我可以更改继承的 AttributeList 的类型以将其扩展为包含每个元素的 value 属性吗? 或者我不应该在 BaseProfile 方面完全继承?

我已经尝试在此处(以及更广泛的互联网)进行搜索,并且有许多有助于简单继承的答案,但我找不到在继承期间更改属性类型的答案。

【问题讨论】:

  • 首先开始支持composition over inheritance。其次,您可以在 Profile-class 中将 AttributeList 设为通用。
  • AttributeList 是基类中的字段时,您不能将其更改为派生类中的属性,除非您使用 隐藏 基实现new-关键字。

标签: c# inheritance properties extends


【解决方案1】:

属性是类的错误名称,请为其选择另一个名称。 (这是一个标准的 .Net 类,最好避免在类名的末尾使用它,因为以属性结尾意味着该类继承自 Attribute)。

    public class Attribute
    {
        public string Name { get; set; }
        public string ShortName { get; set; }
        public bool Standard { get; set; }
    }

    public class BaseAttribute : Attribute
    {
        public int Value { get; set; }
    }

    public class Profile<T> where T:Attribute,new ()
    {
        public List<T> AttributeList = new List<T>
        {
             new T {Name = "Hands", ShortName = "HA", Standard = true},
             new T {Name = "Arms", ShortName = "AR", Standard = true},
        };
    }

    public class BaseProfile : Profile<BaseAttribute>
    {

    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-06-16
    • 2011-03-31
    • 2012-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多