我試過,但我不知道如何甚至谷歌這一點。c#抽象字段作爲屬性和作爲方法返回
今天早上我一直在玩抽象類。 我想要做的是得到(只有一個get
,現在忘記set
)whenused
字段Salutation
到GoodMorning
類〜但要訪問它作爲屬性而不是方法調用。
以下代碼工作得很好。但我會在Main()中使用morn.whenUsed
而不是morn.whenUsed()
。
如果在GoodMorning
,GoodAfternoon
和GoodNight
中需要相同的更改,那很好。但我想這三個類可以在不同的時候使用,但如果不是,那就沒問題了。
這甚至有可能使用抽象?
感謝您的輸入。
namespace AbstractClas
{
class Program
{
static void Main(string[] args)
{
Salutation morn = new GoodMorning("beautiful day");
Salutation aftr = new GoodAfternoon("after lunch comfort food comma");
Salutation nigh = new GoodNight("light and brezzy night");
Console.WriteLine("morn is the saluataion used during the {0}.", morn.whenUsed());
Console.WriteLine("aftr is the saluataion used during the {0}.", aftr.whenUsed().ToUpper());
Console.WriteLine("nigh is the saluataion used during the {0}.", nigh.whenUsed());
if (morn is Salutation)
Console.WriteLine("morn is a Salutation");
if (morn is GoodMorning)
Console.WriteLine("morn is a GoodMorning");
if (morn is GoodAfternoon)
Console.WriteLine("morn is a GoodAfternoon");
else
Console.WriteLine("morn is NOT a GoodAfternoon");
if (morn is GoodNight)
Console.WriteLine("morn is a GoodNight");
else
Console.WriteLine("morn is NOT a GoodNight");
Console.ReadKey();
}
}
internal abstract class Salutation
{
protected string salutation = "";
protected string whenused = "";
internal abstract void salu(string str, string wUsed);
internal abstract string whenUsed();
}
internal class GoodMorning : Salutation
{
internal override void salu(string s, string w) { salutation = s; whenused = w; }
internal GoodMorning(string gm) { salu(gm, "morning".ToUpper()); }
internal override string whenUsed() { return whenused; }
}
internal class GoodAfternoon : Salutation
{
internal override void salu(string s, string w) { salutation = s; whenused = w; }
internal GoodAfternoon(string ga) {
char[] c = "afternoon".ToCharArray();
Array.Reverse(c);
salu(ga, new string(c));
}
internal override string whenUsed() { return whenused; }
}
internal class GoodNight : Salutation
{
internal override void salu(string s, string w) { salutation = s; whenused = w; }
internal GoodNight(string gn) { salu(gn, "night".ToUpper()); }
internal override string whenUsed() { return whenused.ToLower(); }
}
}
不知道我明白你在問什麼。你是否想將'whenUsed'從方法改爲只讀屬性?如果是這樣,你不能把它定義爲內部抽象字符串whenUsed {get; }'在'Salutation'中,並覆蓋它爲'內部覆蓋字符串whenUsed {get {return/*無論具體類想要返回* /; }}'? – KMoussa
屬性可以以與方法 – Fabio
相同的方式被覆蓋@KMoussa您的評論顯示您的操作非常清晰,明白。我明白我做錯了什麼。我沒有實現'{get; }作爲使用Salutation時的財產執行。謝謝。 – Steve