我正在尝试自学C#中的面向对象编程,但我有一个关于何时使用base
的问题。我理解一般原则,但不确定在下面的示例中哪种方法更好。这个简单的测试包括:
- 一个具有两个
string
属性的interface
- 实现此接口并添加了几个其他
string
属性的abstract
类 - 两个实现抽象类的类。其中一个使用
base
,另一个则没有,但它们在执行程序时都会产生相同的输出。
我的问题是:在这个例子中,是否有一种实现比另一种更可取?我不确定TranslationStyleA
和TranslationStyleB
之间是否有任何有意义的区别,或者只是个人喜好?
非常感谢您的时间和想法!
using System;
namespace Test
{
interface ITranslation
{
string English { get; set; }
string French { get; set; }
}
public abstract class Translation : ITranslation
{
public virtual string English { get; set; }
public virtual string French { get; set; }
public string EnglishToFrench { get { return English + " is " + French + " in French"; } }
public string FrenchToEnglish { get { return French + " is " + English + " in English"; } }
public Translation(string e, string f)
{
English = e;
French = f;
}
}
public class TranslationStyleA : Translation
{
public override string English
{
get { return base.English; }
set { base.English = value; }
}
public override string French
{
get { return base.French; }
set { base.French = value; }
}
public TranslationStyleA(string e, string f) : base(e, f)
{
}
}
public class TranslationStyleB : Translation
{
private string english;
public override string English
{
get { return english; }
set { english = value; }
}
private string french;
public override string French
{
get { return french; }
set { french = value; }
}
public TranslationStyleB(string e, string f) : base(e, f)
{
this.English = e;
this.French = f;
}
}
class Program
{
static void Main(string[] args)
{
TranslationStyleA a = new TranslationStyleA("cheese", "fromage");
Console.WriteLine("Test A:");
Console.WriteLine(a.EnglishToFrench);
Console.WriteLine(a.FrenchToEnglish);
TranslationStyleB b = new TranslationStyleB("cheese", "fromage");
Console.WriteLine("Test B:");
Console.WriteLine(b.EnglishToFrench);
Console.WriteLine(b.FrenchToEnglish);
Console.ReadKey();
}
}
}
A
或B
会更可取。再次感谢您快速详细的回复! - Superangel