在构造函数中初始化虚拟属性是错误的吗?

时间:2015-02-07 12:36:04

标签: c# oop inheritance constructor

在构造函数中初始化虚拟属性是错误的吗?它只是感觉不对,因为如果您在派生类中覆盖属性,则首先使用基类构造函数中的值初始化该属性,然后由派生类构造函数再次分配该属性。这样做还有其他选择吗?我在说这样的事情

internal class B1
{
    public B1()
    {
        Ti = "Hello";
    }

    public virtual string Ti { get; set; }
}

internal class B2 : B1
{
    public B2()
    {
        Ti = "HelloKitty";
    }

    public override string Ti { get; set; } //<--"Hello" will be assigned first then "HelloKitty" will be assigned
}

internal class Program
{
    private static void Main(string[] args)
    {
        var b2 = new B2();
        Console.WriteLine(b2.Ti);
        Process.GetCurrentProcess().WaitForExit();
    }
}

更新1: 根据@AK _

的建议
internal class Bb1
{
    private string _ti;

    public Bb1()
    {
        _ti = "Hello";
    }

    public virtual string Ti
    {
        get { return _ti; }
        set { _ti = value; }
    }
}

internal sealed class Bb2 : Bb1
{
    public Bb2()
    {
        Ti = "HelloKitty";
    }

    public override string Ti { get; set; }
}

基类中的变量_ti由“Hello”初始化。 _ti is still in the base class

如果不使用字符串类型我会使用明确需要公开的类型?

1 个答案:

答案 0 :(得分:1)

另一方面,这是合理的(注意B2是密封的)

internal class B1
{
    private string m_ti;
    public virtual string Ti { get{return m_ti;} set{m_ti = value;} }
    public B1()
    {
        m_ti = "Hello";
    }


}

internal sealed class B2 : B1
{
    public B2()
    {
        Ti = "HelloKitty";
    }

    public override string Ti { get; set; } //<--"Hello" will be assigned first then "HelloKitty" will be assigned
}

另一个选项是受保护的构造函数:

internal class B1
{
    private string m_ti;
    public virtual string Ti { get { return m_ti; } set { m_ti = value; } }
    public B1()
    {
        m_ti = "Hello";
    }

    protected B1(String word)
    {
        m_ti = word;
    }
}

internal sealed class B2 : B1
{
    public B2():base("kitty")
    {

    }
}