這是我的類別的僱員,並從員工另一者(這只是一個例子類):有沒有使用新的創建一個實例的另一種方法?
public class Employee
{
public int EmployeeID { get; set; }
public Type type { get; set; }
public string Name { get; set; }
}
public class Manager : Employee
{
public void DoSomething()
{
// Bla bla
}
}
public class Salesman : Employee
{
public void DoAnotherSomething()
{
// Bla bla
}
}
正如你看到的,我的Employee類有一個類型屬性,包含經理或業務員。我不想使用許多開關情況,那麼是否有辦法創建知道類型變量的對象?
UPDATE 1:
好的,我的意思是,在我的真實程序中。我使用的許多開關的情況下創建對象:
Employee employee = new Employee();
// I do somethings to get the values to employee I store it in a Employee list
// Then I need to create the particular object of each one, I need to travel all
// the list an create its instance
switch (employee.Type)
{
case Manager:
employee = new Manager();
// Some stuff
break;
case Salesman:
employee = new Salesman();
// Some stuff
break;
}
在我真正的代碼,我需要使用130箱子,或多或少。所以我想實現另一種避免這種情況的方法。
根據實例的值創建一個類型的實例?這是否像回到過去一樣? –
也許這只是我,但我不明白這個問題。是不是使用'new'創建實例?它試圖避免開關情況(開關櫃是什麼?)?它是關於創建類型變量而不知道它是什麼類型?運營機構能否澄清? – Michael
你可以使用'Activator.CreateInstance'創建一個實例,但是我有一種感覺,如果你認爲這一點,你並不真的想這樣做。你想達到什麼目的? –