如何在创建类对象时自动设置变量的值?

时间:2015-04-24 18:09:35

标签: c# .net winforms

我有一个班级:

public class Test
{
    public string Title { get; set; }
    public Size Size { get; set; }
}

是自定义控件的一部分。当开发人员创建Test对象时,我需要我的班级自动计算Size属性文本的Title

我现在有一个大脑失败,我不知道甚至要搜索什么。我只是为了言语而迷失。

当开发人员创建测试对象时,如何自动测量Title文本的大小:

Test test = new Test()
{
    Title = "This is some text.",
};

我有一些想法,但他们没有工作,我觉得他们有点疯狂,所以我不确定是否应该发布它们。

4 个答案:

答案 0 :(得分:3)

Title属性的setter中执行此操作。当您使用该语法创建Test的实例时,在实例化对象后,您实际上正在通过属性设置器运行。

public class Test
{
    public Size Size { get; set; }

    private string _title;
    public string Title
    {
        get { return _title; }
        set
        {
            _title = value;
            Size = // calculate size of _title
        }
    }
}

答案 1 :(得分:3)

喜欢这个。无论何时调用尺寸,它都会自动为您计算尺寸。

public class Test
{
    public string Title { get; set; }
    public readonly Size Size 
    { 
        get
        {
            return TextRenderer.MeasureText(this.Title, this.Font);
        } 
    }
}

示例:

Test test = new Test()
{
    Title = "This is some text.",
};
var result = test.Size; //Should give you your calculated size when called.

答案 2 :(得分:0)

在构造函数中执行:

public class Test
{
    private string _title = null;
    private Size _size = null;

    public Test(String title)
    {
        Title = title;
    }

    public string Title { get { return _title; }; set { _title = value; _size = TextRenderer.MeasureText(this.Title, this.Font); } }

    public readonly Size Size { get; }
}

答案 3 :(得分:0)

选项A. 使Size成为派生函数。

public class Test
{
    public string Title { get; set; }
    public int Size 
    { 
        get
        {
           return (string.IsNullOrEmpty(Title)) ? 0 : Title.Length;
        } 
    }
}

通过这种方式,尺寸始终与Title同步。

选项B。拦截Title.set 当您更改标题时,大小会更新。

public class Test
{
    private string _title;
    public string Title 
    { 
        get { return _title; } 
        set
        {
            _title = value;
            Size = (string.IsNullOrEmpty(value)) ? 0 : Title.Length;
        } 
    }
    public int Size { get; set; }   
}

PD。对于测量字符串,int应该足够Size(专为2D度量而设计)。