請考慮以下幾點:非常基本的 C#代碼。在C#抽象中設置構造函數
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Random random = new Random();
for (int i = 1; i <= 100; i++)
{
int num = random.Next(1000);
string it_type;
if (num == 666)
{
System.Console.Write("Antichrist/satanistic trips get. Enjoy! ");
JonSkeet technician = new JonSkeet(); // Needs more Super::$tatic
technician.setup();
it_type = technician.getITType();
}
else
{
Whisperity technician = new Whisperity();
technician.setup();
it_type = technician.getITType();
}
System.Console.WriteLine(it_type + "... Prepare for next iteration.");
}
System.Console.ReadLine();
}
}
abstract public class ITTechnician
{
protected string itt_type = "Noname person.";
protected bool isJonSkeet = false;
public string getITType()
{
return this.itt_type;
}
abstract public void setup();
}
public class JonSkeet : ITTechnician
{
public override void setup()
{
this.itt_type = "Jon Skeet";
this.isJonSkeet = true;
}
}
public class Whisperity : ITTechnician
{
public override void setup()
{
this.itt_type = "Whisperity";
this.isJonSkeet = false;
}
}
}
我如何將能夠建立一個構造函數的方式,抽象類(abstract public void
?)需要它,我沒有打電話給technician.setup();
因爲構造需要設置兩個照顧內部變量。如果我調用類的函數同名的類本身,我得到以下錯誤:
Error 1 'Whisperity': member names cannot be the same as their enclosing
而且,我的其他問題是關於優化。有沒有一種方法來定義technician
的if
結構,以便像下面這樣就可以執行外(這將省去具有兩倍classType technician = new classType();
線,或者是在C#它unbypassable?)
string it_type;
// Register 'technician' as a variable here.
if (num = 666)
{
technician = new JonSkeet();
}
else
{
technician = new Whisperity();
}
it_type = technician.getITType();
System.Console.WriteLine(it_type + "...");
@exacerbatedexpert:你不能強制派生類來實現一個consructor,但是你可以強制它在抽象類中調用一個構造函數。如果抽象類沒有默認構造函數,則子類*必須*明確地調用構造函數。 – 2012-08-10 22:27:48