如何在C#

时间:2016-04-25 16:40:36

标签: c#

如何使用以下代码创建对象?我需要在控制台中用这个对象显示一条消息......

class TimePeriod { 
    private double seconds;
    public double Hours { 
        get { return seconds / 3600; } 
        set { seconds = value * 3600; }
    } 
} 

这样的事情是否正确?

TimePeriod time = new TimePeriod(10)

3 个答案:

答案 0 :(得分:2)

在C#中,为了在为对象提供参数的同时构造对象,必须首先使用该参数创建一个构造函数作为输入参数:

class TimePeriod { 
    public TimePeriod(double seconds) {
        this.seconds = seconds;
    }
    private double seconds;
    public double Hours { 
        get { return seconds / 3600; } 
        set { seconds = value * 3600; }
    } 
} 

然后您可以使用上面建议的语法:

TimePeriod period = new TimePeriod(10);

答案 1 :(得分:1)

你会像这样创建一个新对象:

TimePeriod myObject = new TimePeriod();

在拥有构造函数时,在括号中添加10非常有用。阅读这些以获取更多信息,它们非常简单。

我不知道你想写什么到控制台,但它会像这样:

Console.WriteLine("The amount of hours is {0}", myObject.Hours);

希望这是有道理的:)

答案 2 :(得分:0)

class TimePeriod 
{ 
    private double seconds;

    public TimePeriod (double dSeonds)
    {
        seconds=dSeonds;
        Console.WriteLine("Object Created: "+dSeonds);
    }

    public double Hours { 
        get { return seconds / 3600; } 
        set { seconds = value * 3600; }
    } 
}

使用以下内容创建上述类的Object

TimePeriod period = new TimePeriod(10);