扩展继承的属性C#

时间:2018-08-28 09:53:59

标签: c# inheritance properties extends

我有一个从基类继承的类

还有另外两个类,它们具有这些原始类的列表作为属性

我认为这两个新类应该具有继承性,但似乎无法使事情发挥作用。

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?

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

1 个答案:

答案 0 :(得分:0)

属性是该类的错误名称,请为其选择另一个名称。 (这是一个标准的.Net类,最好甚至在类名的末尾也避免使用它,因为以attribute结尾表示该类是从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>
    {

    }