如何在基类上使用派生属性?

时间:2014-06-03 14:06:17

标签: c# inheritance

我有一个基类,它有一个属性和一个使用该属性的方法。我有一个继承该基类的类,并且有自己的基类属性实现,使用New修饰符显式隐藏。在基类的方法中,是否有一种使用继承类'属性而不是基类实现的好方法?

class Program
{
    public class MyBase
    {
        public string MyProperty { get { return "Base"; } }

        public string MyBaseMethod()
        {
            return MyProperty;
        }
    }

    public class MyInherited : MyBase
    {
        public new string MyProperty { get { return "Inherited"; } }
    }

    static void Main(string[] args)
    {
        List<MyBase> test = new List<MyBase>();
        test.Add(new MyBase());
        test.Add(new MyInherited());

        foreach (MyBase item in test)
        {
            Console.WriteLine(item.MyBaseMethod());
        }
    }
}

在示例中,输出为: 基础 基

目前的解决方法:

    ...
    public class MyBase
    {
        public string MyProperty { get { return "Base"; } }
        public string MyBaseMethod()
        {
            if (this is MyInherited)
            {
                return baseMethod(((MyInherited)this).MyProperty);
            }
            else
            {
                return baseMethod(MyProperty);
            }
        }

        private string baseMethod(string input)
        {
            return input;
        }
    }
    ...

有更好的方法吗?我宁愿不必做明确的类型转换。

3 个答案:

答案 0 :(得分:5)

通常应避免使用new关键字隐藏成员。而是使基类'property virtual并在降序类中覆盖它。 MyBaseMethod将在继承类时自动使用此重写属性。

public class MyBase
{
    public virtual string MyProperty { get { return "Base"; } }

    public string MyBaseMethod()
    {
        return MyProperty;
    }
}

public class MyInherited : MyBase
{
    public override string MyProperty { get { return "Inherited"; } }
}

var inherited = new MyInherited();
Console.WriteLine(inherited.MyBaseMethod()); // ==> "Inherited"

查看与new关键字相关的这篇有趣帖子:Why do we need the new keyword and why is the default behavior to hide and not override?

答案 1 :(得分:2)

使属性变为虚拟,而不是密封,并覆盖它,而不是遮蔽它。然后,属性的所有使用将使用它的最派生实现。

答案 2 :(得分:0)

没有这样的方法。如果你做了新的(早期绑定),你必须进行显式的强制转换。唯一的解决方案是使属性成为虚拟。然后你可以覆盖它(使用覆盖修饰符)。这是后期绑定。

相关问题