2017-03-10 24 views
2

我已经使用了一个接口来提供2个值,即IDName到类EmployeeStudent。此后,我使用了一个类型接口函数来选择应选择这两个类中的哪一个,然后在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(); 
    } 
} 
+0

您是否在问如何使用您的'idata'作为'Employee'对象? –

+0

@Dan我问,如何在从idata对象提供值时访问员工成员方法 – Im786

回答

0

如果你想用你的IData对象为Employee对象,你要投它。当然,你应该检查一下确保演员的角色是否合理。使用这里的as运营商和测试空都将检查你的对象实际上是一个Employee并且将它转换为,如果是

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(); 

    var employee = idata as Employee; 
    if (employee != null) 
    { 
     employee.getDetails(); 
    } 
    //Console.WriteLine("Id={0} & Name={1}", idata.ID, idata.Name); 
    Console.WriteLine(idata.GetType()); 
    Console.ReadLine(); 
} 

使用您的示例程序,你可以做这样的事情。你可以做一个直接演员(例如((Employee)idata).getDetails(),但是如果演员失败了,那么演员可能会抛出一个异常(并且因为你犯了一个错误或者因为未来的执行者会以你现在不期望的方式行事) )

+0

非常感谢!想到铸造,但不知何故,它只是没有击中正确的电源线,但是,代码工作得很好,再次感谢,你能提出解决这个问题的更好方法吗? – Im786

+0

这是一个非常典型的模式 - 尽管它可能更好地为你的接口提供更好的名字('IPerson'?'IPersonWithIdentifier'?)。无论如何,很高兴hel p - 考虑将此标记为已接受的答案,并/或提出是否有帮助。 –

+1

当然,我不能高调,因为我在声望点上很低,但已被标记为接受的答案,再次感谢。 – Im786