如何在基类中封装属性
本文关键字:封装 属性 基类 | 更新日期: 2023-09-27 18:31:47
我的场景是关于开发数学问题的。作为一个IProblem
接口,我认为它应该包含的两个主要属性是 QuestionText
和 Response
. QuestionText
始终是一个字符串,但Response
有时可以是复杂对象(自定义Fraction
struc)或其他数据类型,如字符串、十进制、整数等。
public interface IProblem
{
string QuestionText { get; set; }
object Response { get; }
bool IsComplete();
bool IsCorrect();
}
如您所见,Response
是对象。我猜到这种数据类型是因为所有问题本质上都有一个响应。由于它是一个对象,我只为将来的错误(转换问题)定义 get。
我的想法是后来,在一个具体的类中访问这个属性(Response
),而无需铸造。看看?
public abstract class Problem : IProblem
{
public string QuestionText { get; set;}
public object Response { get; protected set; }
public virtual bool IsComplete()
{
return true;
}
public abstract bool IsCorrect();
}
public class BinaryProblem : Problem
{
public decimal N1 { get; set; }
public decimal N2 { get; set; }
public decimal Response
{
get { return (decimal)base.Response; }
set { base.Response = value; }
}
public override bool IsCorrect()
{
return N1 + N2 == Response;
}
}
在这里,我正在测试值。
static void Main(string[] args)
{
BinaryProblem p = new BinaryProblem();
p.N1 = 2;
p.N2 = 4;
p.Response = 6;
IProblem p2 = p;
Console.WriteLine(p2.Response);
Console.WriteLine(p2.IsComplete().ToString());
}
到目前为止,它仍然有效,但我想知道我正在做的事情是否正确或是一种好的做法。我见过另一个人使用new
运算符来做到这一点。其他人不使用base
这个词。
这是个好办法吗?它会导致将来的错误吗?请给我一个关于我的设计的反馈。
编辑:确实有必要在非通用接口中访问响应。
也许你正在寻找这样的东西?请注意,我省略了一些东西,因为它们对问题的通用解决方案部分(如 QuestionText)并不重要。我还省略了基类,因为它看起来只不过是一个传递,以及一个额外的、不必要的层。这可能不完全是你要找的,但我希望它能帮助你到达那里。
首先,这是所有内容的使用方式:
编辑:注意现在如何将它们都视为非通用的IProblem。
private static void StackOverflowQuestion()
{
IProblem<int> problem1 = new IntProblem(2, 4);
problem1.Response = 6;
IProblem<decimal> problem2 = new DecimalProblem(5, 10);
problem2.Response = .5M;
Console.WriteLine("Problem 1 is correct: {0}", problem1.IsCorrect());
Console.WriteLine("Problem 2 is correct: {0}", problem2.IsCorrect());
List<IProblem> problems = new List<IProblem>();
problems.Add(problem1);
problems.Add(problem2);
problems.ForEach(problem => Debug.WriteLine(problem.GetResponse()));
}
编辑:这是非通用接口,因此可以在列表中使用许多问题并以相同的方式处理:
public interface IProblem
{
object GetResponse();
}
这是界面:
编辑:请注意,这现在实现了非泛型接口。
public interface IProblem<T> : IProblem
{
T Response { get; set; }
bool IsCorrect();
}
以下是课程:
编辑:注意新的 GetResponse() 方法。
public class IntProblem : IProblem<int>
{
private int _number1 { get; set; }
private int _number2 { get; set; }
public int Response { get; set; }
public IntProblem(int number1, int number2)
{
this._number1 = number1;
this._number2 = number2;
}
public bool IsCorrect()
{
return this._number1 + this._number2 == Response;
}
public object GetResponse()
{
return this.Response;
}
}
public class DecimalProblem : IProblem<decimal>
{
private decimal _number1 { get; set; }
private decimal _number2 { get; set; }
public decimal Response { get; set; }
public DecimalProblem(decimal number1, decimal number2)
{
this._number1 = number1;
this._number2 = number2;
}
public bool IsCorrect()
{
return this._number1 / this._number2 == Response;
}
public object GetResponse()
{
return this.Response;
}
}