【问题标题】:Properties or Methods? [duplicate]属性还是方法? [复制]
【发布时间】:2012-06-21 23:24:33
【问题描述】:

可能重复:
Properties vs Methods

我是一名初学者 C# 程序员,最近发现了如何使用属性来公开成员。但是,当返回某些东西时,我对何时将属性与方法相对使用感到困惑。

我应该这样做吗:

public Vector2 Center {
    get {
        Vector2 screenDem = new Vector2(game.GraphicsDevice.Viewport.Width,
            game.GraphicsDevice.Viewport.Height);
        return new Vector2(screenDem.X / 2, screenDem.Y / 2);
    }
}

或者我应该这样做:

public Vector2 GetScreenCenter() {
    Vector2 screenDem = new Vector2(game.GraphicsDevice.Viewport.Width,
            game.GraphicsDevice.Viewport.Height);
    return new Vector2(screenDem.X / 2, screenDem.Y / 2);
}

我什么时候应该使用哪个以及为什么?

也许我只是想得太用力了,没关系,我不知道。

谢谢。

【问题讨论】:

  • 归根结底,您的两种方法是等效的。
  • @KirkWoll。这显然不是一个重复,这个问题是properties 方法,而您的链接是properties vs方法。变得真实! :)

标签: c# properties methods


【解决方案1】:

如果您只想获取和设置一个值,那么最好使用属性。

public DateTime TheCurrentTime {get; set;}

如果您需要传递参数以修改或返回某些内容,那么最好使用方法。

public DateTime HowManyDaysUntilMyBirthday(Datetime MyBirthday) 
{
    return (MyBirthday - DateTime.Now());
}

【讨论】:

    猜你喜欢
    • 2014-04-11
    • 2014-08-29
    • 1970-01-01
    • 2011-08-16
    • 1970-01-01
    • 1970-01-01
    • 2011-09-12
    • 2011-05-24
    相关资源
    最近更新 更多