次の非常に基本的な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;
}
}
}
コンストラクターが 2 つの内部変数の設定を処理するため、抽象クラス ( abstract public void
?) が必要とし、呼び出す必要がない方法でコンストラクターを設定するにはどうすればよいでしょうか。technician.setup();
クラス関数をクラス自体と同じ名前で呼び出すと、次のエラーが発生します。
エラー 1 'Whisperity': メンバー名はそれらを囲んでいるものと同じにすることはできません
また、私の他の質問は最適化についてです。次のようなものを実行できるように、コンストラクトtechnician
の外側で定義する方法はありますか?if
classType technician = new classType();
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 + "...");