-1

In the past few days I've been reading about the differences betweeen properties and methods in C# and when use each. Most of the articles/questions I read says that getters should be "light" and never have large amount of logic or complex operations inside.

Right now I have a get that I think is on the line between property and method, so I would like to see what you all think, if I should change to method or stay with the getter.

Also any other advice is welcome :D

public decimal[] getPreprocData
{
    get
    {
        int i = 3;
        decimal[] data = new decimal[9];

        data[0] = (start.Value.Hour * 3600) + (start.Value.Minute * 60);
        data[1] = duration.Value;
        data[2] = flowRate.Value;

        foreach (NumericUpDown nud in gbHTF.Controls.OfType<NumericUpDown>().OrderBy(nud => nud.TabIndex))
        {
            data[i] = nud.Value;
            i++;
        }

        return data;
    }
}
4

3 回答 3

6

Properties&Field一般是Nounmethods&functions一般是Verb

所以,getPreprocData应该是一个method。因为它代表了对对象(类)实例的操作。


从我自己的角度来看,由于您的财产从不使用setter,所以总是比使用method更好property

当没有什么可设置的时候,拥有一个属性有什么意义。?


您的属性可以作为方法实现:

public decimal[] GetPreprocData()
{
        int i = 3;
        decimal[] data = new decimal[9];

        data[0] = (start.Value.Hour * 3600) + (start.Value.Minute * 60);
        data[1] = duration.Value;
        data[2] = flowRate.Value;

        foreach (NumericUpDown nud in gbHTF.Controls.OfType<NumericUpDown>().OrderBy(nud => nud.TabIndex))
        {
            data[i] = nud.Value;
            i++;
        }

        return preprocData;
}
于 2013-03-06T18:56:26.493 回答
1

这看起来确实应该是一种方法。

您正在进行一些初始化,并且 的大小gbHTF.Controls是无限的,因此最终可能会很昂贵。

它还隐藏在一个实际上并没有描述你在做什么的属性名称后面——这作为一种描述性方法会更好。

于 2013-03-06T18:56:19.927 回答
0

将其转换为方法。那里有处理和业务逻辑。

通常,我会将属性限制为其他属性的格式或组合,这样您就可以清楚地分离关注点。

于 2013-03-06T18:56:16.617 回答