gpt4 book ai didi

c#:初学者CLASS构造函数问题

转载 作者:行者123 更新时间:2023-11-30 13:20:49 25 4
gpt4 key购买 nike

public class ElapsedTime
{
public int hours;
public int minutes;
public void ElapsedTime(int h, int m)
{
hours = h;
minutes = m;
}
}

从另一个事件我这样做:

    ElapsedTime BeginningTime = new ElapsedTime();

我将如何初始化hm

当我尝试这样做时:BeginningTime.ElapsedTime(7, 7);

它给我这个错误:

Error 1 'ElapsedTime': member names cannot be the same as their enclosing type

我想要的只是一个带有接受初始化值的构造函数的类。我希望能够调用它。

更新:

现在我有:

 public class ElapsedTime
{
private int hours;
private int minutes;
public ElapsedTime(int h, int m)
{
hours = h;
minutes = m;
}
}

它在 public ElapsedTime(int h, int m)

上给我同样的错误

最佳答案

省略 void。将它放在那里,就是在声明它是一种方法,而不是构造函数。

public class ElapsedTime
{
public int hours;
public int minutes;
public ElapsedTime(int h, int m)
{
hours = h;
minutes = m;
}
}

然后创建一个实例只是调用构造函数的问题。

ElapsedTime BeginningTime = new ElapsedTime(7, 7);

关于c#:初学者CLASS构造函数问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3972165/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com