我试图覆盖类常量变量,但我的方法不起作用。
以下代码:
// The following line of code should output "DATE: 9/9/2014"
// But it outputs: "DATE: 31/3/2015"
CustomDateChecker.checkUsedByDate();
在下面的课程中;如何覆盖变量USED_BY_YEAR
,USED_BY_MONTH
和USED_BY_DAY
?
public class DateChecker
{
public const uint USED_BY_YEAR = 2015;
public const uint USED_BY_MONTH = 3;
public const uint USED_BY_DAY = 31;
public static bool checkUsedByDate()
{
TaskDialog.MessageBox.Show(string.Format("DATE: {0}/{1}/{2}", USED_BY_DAY, USED_BY_MONTH, USED_BY_YEAR));
}
}
public class CustomDateChecker : DateChecker
{
// Override Date
public const uint USED_BY_YEAR = 2014;
public const uint USED_BY_MONTH = 9;
public const uint USED_BY_DAY = 9;
}
修改:在阅读建议后,我已将变量更改为static readonly
而不是const
。但不幸的是它同样的问题,日期并没有改变。使用static readonly
可能的解决方案吗?
public class DateChecker
{
public static readonly uint USED_BY_YEAR = 2015;
public static readonly uint USED_BY_MONTH = 3;
public static readonly uint USED_BY_DAY = 31;
public static bool checkUsedByDate()
{
TaskDialog.MessageBox.Show(string.Format("DATE: {0}/{1}/{2}", USED_BY_DAY, USED_BY_MONTH, USED_BY_YEAR));
}
}
public class CustomDateChecker : DateChecker
{
// Override Date
public static new readonly uint USED_BY_YEAR = 2014;
public static new readonly uint USED_BY_MONTH = 9;
public static new readonly uint USED_BY_DAY = 9;
}
答案 0 :(得分:1)
public class DateChecker
{
public readonly uint USED_BY_YEAR = 2015;
public readonly uint USED_BY_MONTH = 3;
public readonly uint USED_BY_DAY = 31;
public DateChecker()
{
}
public DateChecker(uint d, uint m, uint y)
{
this.USED_BY_DAY = d;
this.USED_BY_MONTH = m;
this.USED_BY_YEAR = y;
}
public bool checkUsedByDate()
{
Console.WriteLine(string.Format("DATE: {0}/{1}/{2}", USED_BY_DAY, USED_BY_MONTH, USED_BY_YEAR));
return false;
}
}
public class CustomDateChecker : DateChecker
{
// Override Date
public new const uint USED_BY_YEAR = 2014;
public new const uint USED_BY_MONTH = 9;
public new const uint USED_BY_DAY = 9;
public CustomDateChecker()
: base(USED_BY_DAY, USED_BY_MONTH, USED_BY_YEAR)
{
}
}
private static void Main(string[] args)
{
CustomDateChecker d = new CustomDateChecker();
d.checkUsedByDate();
}
答案 1 :(得分:0)
看看以下示例是否有帮助。
public class DateChecker
{
public virtual uint USED_BY_YEAR { get; set; }
public virtual uint USED_BY_MONTH { get; set; }
public virtual uint USED_BY_DAY { get; set; }
public DateChecker()
{
USED_BY_YEAR = 2015;
USED_BY_MONTH = 3;
USED_BY_DAY = 31;
}
public virtual void checkUsedByDate()
{
Console.Write(string.Format("DATE: {0}/{1}/{2}", USED_BY_DAY, USED_BY_MONTH, USED_BY_YEAR));
}
}
public class CustomDateChecker : DateChecker
{
public override uint USED_BY_DAY
{
get
{
return 9;
}
set
{
base.USED_BY_DAY = value;
}
}
public override uint USED_BY_MONTH
{
get
{
return 9;
}
set
{
base.USED_BY_MONTH = value;
}
}
public override uint USED_BY_YEAR
{
get
{
return 2014;
}
set
{
base.USED_BY_YEAR = value;
}
}
}
class Program
{
static void Main(string[] args)
{
new CustomDateChecker().checkUsedByDate();
}
}