如何从父级获取子类的属性值?

时间:2020-02-24 16:09:40

标签: c#

我有一个名为Template的基类。而且我有许多子类,例如TemplateChild1TemplateChild2等继承了Template类的子类。所有子类基本上具有相同的结构,如下所示:

public class TemplateChild1 : Template
{
    public const string Name = "Child class 1";
    //many other properties
}

public class TemplateChild2 : Template
{
    public const string Name = "Child class 2";
    //many other properties
}

//and many more other child classes with similar structure

在我的任务中,我必须在表单上的Template中显示ComboBox类的所有这些子类。为此,我使用了以下代码:

var templateTypes = Assembly
                    .GetAssembly(typeof(Template))
                    .GetTypes()
                    .Where(t => t.IsSubclassOf(typeof(Template))).ToList();

然后我将此列表放在ComboBox上,它工作正常。但是在ComboBox中,我仅看到该类的开发名称,而没有看到Name属性的值。例如,代替“ Child class 1” /“ Child class 2” / etc。 ,我看到了TemplateChild1 / TemplateChild2 / etc。我该如何解决这个问题?

2 个答案:

答案 0 :(得分:4)

您对继承的观念有些颠倒。如果Child1和Child2都具有“名称”属性,则将“名称”设为父级的属性(所有子级都具有“名称”),然后可以将所有子级视为它们的父级实例,并获取名称

List<Parent> x = new List<Parent>();

x.Add(new TemplateChild1());
x.Add(new TemplateChild2());

myCombo.DataSource = x;
myCombo.DisplayMember = "Name"; //tell databinding to use the Name property for the displaytext

对于以下课程的设置:

public class Parent{
    public string Name { get; protected set; }
}

public class TemplateChild1: Parent
{
    public TemplateChild1(){
        Name = "Child one";
    }
}

public class TemplateChild2: Parent
{
    public TemplateChild2(){
        Name = "Child two";
    }
}

现在,组合中的所有项目(无论是Child1还是Child2)都将显示分配给其Name属性的文本。 set受保护;它只能由父母的孩子访问。子代的构造函数设置Name的值,然后不能将其设置为其他值(嗯..另一个子代除外。如果要防止这种情况,请使子代不可继承),因此它现在是常量

答案 1 :(得分:1)

为详细说明其他答案,该问题最初使用常量。您无法使用基类执行此操作,但是可以使属性readonly至少可以防止将它们写到基类构造函数之外。

public class Template
{
    public string Name { get; }

    public Template(string name)
    {
        Name = name;
    }
}

public class TemplateChild1: Template
{
    public TemplateChild1()
        : base("Child one")
    { }
}