谁会打电话? 无关的代码来解决问题。不是最好的编辑工具,所以简洁。感谢。
新方法无法访问作为派生类一部分的新方法 宾语。所有Intellisense看到的都是基类的抽象部分。将它们键入并运行它们会出错。如果不能添加方法和字段,那么基础点和派生点是什么。我搜索了所有的例子,然后空了。
public class SalesEmployee : Employee
{
public decimal salesbonus; // Additional field
public SalesEmployee(string name, decimal basepay, decimal salesbonus)
{
this.salesbonus = salesbonus; // Create new field
}
public override decimal CalculatePay() // Override abstract
{
return basepay + salesbonus;
}
public decimal CalculateExtraBonus() // Not an override
{
return basepay + (0.5 * salesbonus); // Belongs to this class only
}
}
static void Main()
{
// Create new employee.
SalesEmployee employee1 = new SalesEmployee("Alice", 1000, 500);
decimal = employee1.CalculateExtraBonus(); // Can't see the new method
// Derived class cannot get to new method.
}
我想尝试以下方法。输入问题确实有帮助。
{ SalesEmployee salesEmpInstance = employee1
decimal = salesEmpInstance.CalculateExtraBonus()
// Maybe this could see the method.
答案 0 :(得分:0)
我会忽略语法错误,并假设您在实际代码中使用它。但是,您似乎忘记在派生类构造函数上调用父构造函数(“base”),然后尝试访问仅由父实例化实例化的变量。您还需要将文字“0.5”转换为小数。
You can read more about "base" on msdn
工作代码如下。输出为1250。
using System;
public abstract class Employee
{
public string name;
public decimal basepay;
public Employee(string name, decimal basepay)
{
this.name = name;
this.basepay = basepay;
}
public abstract decimal CalculatePay();
}
public class SalesEmployee : Employee
{
public decimal salesbonus; // Additional field
// -->ERROR HERE, You forgot to call the base and instantiate
// the fields of the parent.
public SalesEmployee(string name, decimal basepay, decimal salesbonus): base(name, basepay)
{
this.salesbonus = salesbonus; // Create new field
}
public override decimal CalculatePay() // Override abstract
{
return basepay + salesbonus;
}
public decimal CalculateExtraBonus() // Not an override
{
return basepay + ((decimal)0.5 * salesbonus); // Belongs to this class only
}
}
class Program
{
static void Main(string[] args)
{
SalesEmployee employee1 = new SalesEmployee("Alice", 1000, 500);
decimal aliceBonus = employee1.CalculateExtraBonus();
Console.WriteLine(aliceBonus);
}
}
答案 1 :(得分:0)
您的代码看起来不错,我建议您:
first class library
。new project
的引用
first class library
first class library
中的new project
dll文件,也许您引用了旧版本的dll。您应该引用最后创建的first class library
{
SalesEmployee employee1 = new SalesEmployee("Alice", 1000, 500);
SalesEmployee salesEmpInstance = employee1 ;
decimal result = salesEmpInstance.CalculateExtraBonus();
}
无论如何,如果您在这种情况下没有任何参考。将以下代码与您的代码进行比较。我测试了它。它有效......
注1:您应该在构造函数中使用base
将name
和basepay
传递给基类中的相应字段。
注2:现在Rebuild
您的项目,有任何错误吗?我还没有!你有VS Intellisense
问题吗?