VS2010调试时,总是属性执行不了,Hour Min Second 的值在类中是有值,跳回Main () 就清零了, 新手跪求大神指点一下!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 类的使用加强
{
class Time
{
private int hour;//字段的定义
private int min;
private int second;
private void SetTime(int h, int m, int s)//方法
{
int Hour = h;
int Min = m;
int Second = s;
}
public Time()//无参构造函数1
{
SetTime(0, 0, 0);
}
public Time(int HourValue)//有参构造函数2
{
SetTime(HourValue, 0, 0);
}
public Time (int HourValue, int MinValue, int SecondValue)//有参构造函数3
{
SetTime(HourValue, MinValue, SecondValue);
}
public int Hour//属性
{
get { return hour; }
set { hour = (value > 0 && value <= 24) ? value : 0; }
}
public int Min
{
get { return min; }
set { min = (value > 0 && value <= 24) ? value : 0; }
}
public int Second
{
get { return second; }
set { second = (value > 0 && value <= 24) ? value : 0; }
}
public string ToString24()//z转化为24进制的方法
{
string output =Hour + ":" + Min + ":" + Second;
return output;
}
public string ToString12()//转化为12进制的方法
{
int hourtemp = (Hour == 12 || Hour == 0) ? 12 : (Hour % 12);
string AMPM = (Hour > 12 ? "PM" : "AM");
string output = hourtemp + ":" + Min + ":" + Second + AMPM;
return output;
}
}
class Programe//main 主函数的开始
{
static void Main(string[] args)
{
Time time1 = new Time();
Console.WriteLine("time1:");
Console.WriteLine("24小时制:" + time1.ToString24());
Console.WriteLine("12小时制:" + time1.ToString12());
Time time2 = new Time(22);
Console.WriteLine("time2:");
Console.WriteLine("24小时制:" + time2.ToString24());
Console.WriteLine("12小时制:" + time2.ToString12());
Time time3 = new Time(22, 36, 30);
Console.WriteLine("time3:");
Console.WriteLine("24小时制:" + time3.ToString24());
Console.WriteLine("12小时制:" + time3.ToString12());
Console.ReadKey();
}
}
}
private void SetTime(int h, int m, int s)//方法
{
//这个才是用属性获取值,原来你的是用方法体内的局部变量获取值
Hour = h;
Min = m;
Second = s;
}
变量作用域问题
感谢!受教了!
private void SetTime(int h, int m, int s)//方法
{
hour = h;
min = m;
second = s;
}
你的写法没有给Hour/Min/Second 三个属性赋值,所以你获取值的时候就会有问题