[英]C# Delegate and Events
我第一次与代表和活动合作并提供帮助。 当程序运行时,如果 gpa 比原来增加,它应该以蓝色显示文本,如果 gpa 下降,则显示红色。 我必须使用两个事件IncreaseGpaEvent 和DecreaseGpaEvent。 必须有一个颜色变量并在 ToString() 中分配。 任何帮助是极大的赞赏。
public delegate void UpdateGPADelegate(string ConsoleColor);
class Student
{
// Fields
private string studentName;
private double gpa;
public string ConsoleColor;
public event UpdateGPADelegate IncreaseGpaEvent;
public event UpdateGPADelegate DecreaseGpaEvent;
// Properties
public string StudentName { get; set; }
public double GPA
{
get { return gpa; }
set
{
IncreaseGpaEvent += onUpdate;
if (!(value > gpa))
{
gpa = value;
IncreaseGpaEvent("Red");
}
DecreaseGpaEvent += onUpdate;
if(!(value < gpa))
{
gpa = value;
DecreaseGpaEvent("Blue");
}
}
}
public Student(string studentName, double gpa)
{
this.studentName = studentName;
this.gpa = gpa;
}
public void onUpdate(double value)
{
if (value < gpa)
{
ConsoleColor = "Red";
}
if (value > gpa)
{
ConsoleColor = "Blue";
}
}
public override string ToString()
{
string str;
str = string.Format($"Name: {StudentName} GPA: {GPA}");
return str;
}
}
尝试这个..
public delegate void UpdateGPADelegate(double ConsoleColor);
class Student
{
// Fields
// private string studentName;
private double gpa;
public string ConsoleColor;
public event UpdateGPADelegate IncreaseGpaEvent;
public event UpdateGPADelegate DecreaseGpaEvent;
// Properties
public string StudentName { get; set; }
public double GPA
{
get { return gpa; }
set
{
if (!(value > gpa))
{
IncreaseGpaEvent(value);
gpa = value;
}
if(!(value < gpa))
{
DecreaseGpaEvent(value);
gpa = value;
}
}
}
public Student(string studentName, double gpa)
{
this.studentName = studentName;
this.gpa = gpa;
IncreaseGpaEvent += onUpdate;
DecreaseGpaEvent += onUpdate;
}
public void onUpdate(double value)
{
if (value < gpa)
{
ConsoleColor = "Red";
}
if (value > gpa)
{
ConsoleColor = "Blue";
}
}
public override string ToString()
{
string str;
str = string.Format($"Name: {StudentName} GPA: {GPA} ConsoleColor: {ConsoleColor}");
return str;
}
}
我修复的代码有问题,就像您在引发事件后为 gpa 赋值一样,这些事件永远不会更大或更小,并且委托的签名也是错误的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.