只是为了练习,我正在尝试编写一个计算器程序。为了使它变得困难,我尝试使用一些我学过但没有真正使用的高级继承主题。假设您有一个IMath
使用一种方法命名的接口string DoMath()
。是否可以在接口中写入一个变量IMath
,所有实现该接口的类都会看到新值?因此,例如,我的类Add : IMath
将具有该方法DoMath()
,并且在该DoMath()
方法中将更改变量的值double ITotal
,所有实现 IMath 接口的类都会看到新值。
问问题
255 次
3 回答
5
不能在接口中指定变量或字段,只能指定:
- 方法
- 特性
- 索引器
- 活动
有关这方面的更多信息,请参阅有关接口的 C# 文档。
接口规定了预期的行为,而不规定了预期的实现。属性可以理解为“检索 X 值的能力”或“提供 X 值的能力”,而变量则是“存储 X 的能力”。这不是一回事,接口不能保证。
如果你绝对需要强制变量的存在,你应该使用基类。我可能会考虑结合这些东西,使用外部接口的接口(即我的计算器应该如何运行)和基类和继承以避免一遍又一遍地重写相同的代码。
于 2013-03-28T11:06:11.807 回答
1
听起来您正在寻找的是一个抽象基类。
您所描述的一种可能的实现如下所示。
public abstract class MathBase
{
public double Total { get; protected set; }
public abstract string DoMath(double value);
protected double ParseValue(string value)
{
double parsedValue;
if (!double.TryParse(value, out parsedValue))
{
throw new ArgumentException(string.Format("The value '{0}' is not a number.", value), "value");
}
return parsedValue;
}
}
public class Add : MathBase
{
public override string DoMath(string value)
{
Total += ParseValue(value);
return Convert.ToString(Total);
}
}
如果您希望继承自的每个类的每个实例MathBase
共享相同的Total
值,您可以将其声明为static
:
public abstract class MathBase
{
public static double Total { get; protected set; }
public abstract string DoMath(string value);
}
(虽然我不太确定你为什么想要这个)
于 2013-03-28T11:03:36.243 回答
0
你可以这样做:
interface IMath
{
string DoMath();
}
abstract class MathBase : IMath
{
protected double Total { get; set; }
public abstract string DoMath();
}
class Add : MathBase
{
public override string DoMath()
{
this.Total = 2;
return "2";
}
}
于 2013-03-28T11:08:27.233 回答