如何在更新课程时更新显示文本长度的属性?

时间:2012-01-05 03:32:55

标签: c#

我有以下课程。请注意,有些键值未显示:

namespace Storage.Models
{
    public abstract class AuditableTable 
    {
        public string Title { get; set; }
        public string Text { get; set; }
    }

}

我想将Text属性的长度存储在名为TextLength的变量中。我是否可以在创建类的实例或更新类时自动执行此操作?

2 个答案:

答案 0 :(得分:3)

您只需添加一个带有getter的属性:

public abstract class AuditableTable 
{
    public string Title { get; set; }
    public string Text { get; set; }

    public int TextLength
    {
        get { return this.Text.Length; }
    }
}

答案 1 :(得分:1)

除非您想记录初始值,否则您不一定需要属性:

    public int TextLength
    {
        get
        {
            return this.Text.Length;
        }
    }

但是,如果你想记录初始长度,你可以这样做:

    string m_Text;

    public string Text
    {
        get
        {
            return m_Text;
        }
        set
        {
            m_Text = value;
            if (m_TextLength == 0)
            {
                m_TextLength = value.Length;
            }
        }
    }

    private int m_TextLength;

    public int TextLength
    {
        get
        {
            return m_TextLength;
        }
    }