我已經使用了一個接口來提供2個值,即ID
和Name
到類Employee
和Student
。此後,我使用了一個類型接口函數來選擇應選擇這兩個類中的哪一個,然後在Main()
中提供這些值。現在重點是,我想在Employee
類的函數中使用這些值。但不知何故,我沒有得到,如何訪問此函數,因爲類型接口的對象將不允許我訪問對象如果我創建一個新的對象,我提供的值不再存在。那麼做這件事的正確方法是什麼? Plz幫助!我的代碼中接口使用的清晰度
interface IData
{
int ID { get; set; }
string Name { get; set; }
}
class Employee : IData
{
public int ID { get; set; }
public string Name { get; set; }
public void getDetails()
{
Console.WriteLine("Emp"+ID);
}
}
class Student : IData
{
public int ID { get; set; }
public string Name { get; set; }
}
class Choice
{
public IData Fetch(bool Flag)
{
if (Flag == true)
{
Employee em = new Employee();
return em;
}
else
{
Student st = new Student();
return st;
}
}
}
class Program
{
static void Main(string[] args)
{
Choice ch=new Choice();
IData idata = ch.Fetch(true);
Console.WriteLine("Enter ID and Name:");
idata.ID = int.Parse(Console.ReadLine());
idata.Name = Console.ReadLine();
//Console.WriteLine("Id={0} & Name={1}", idata.ID, idata.Name);
Console.WriteLine(idata.GetType());
Console.ReadLine();
}
}
您是否在問如何使用您的'idata'作爲'Employee'對象? –
@Dan我問,如何在從idata對象提供值時訪問員工成員方法 – Im786