如何检查各种“是”条件并相应地进行类型转换?

时间:2015-10-15 19:29:52

标签: c#

我有三个班,叫做学校,老师和学生。现在让我们说我有一个名为GetAcademicDetailsOfCity()的方法,它将产生学校,教师和学生中任何类型的对象,或者可以是由三个中的任何一个派生的类。

在运行时,我想查看以下内容:

var instance = GetAcademicDetailsOfCity();
if (instance is School)
{
     //What i actually want is something like  
      var result = new School();   
      result.property1 = (School)instance.property1  
      result.property2 = (School)instance.property2  
      result.property3 = (School)instance.property3  
}

if (instance is Teacher)
{
      var result = new Teacher();  
      result.property1 = (Teacher)instance.property1  
      result.property2 = (Teacher)instance.property2  
      result.property3 = (Teacher)instance.property3  
}

if (instance is Student)
{
      var result = new Student();
      result.property1 = (Student)instance.property1  
      result.property2 = (Student)instance.property2  
      result.property3 = (Student)instance.property3 
}

如何一次检查上述条件

if (instance is School || instance is Teacher || instance is Student)
{
      //What should be the casting of instance below ??
      var result = (????)instance;
}
return result;

通过这个结果实例,我将创建一个特定学校城市学生的报告。如果需要更多详细信息,请告诉我。我很乐意尽可能多地提供详细信息:)。

3 个答案:

答案 0 :(得分:1)

如果GetAcademicDetailsOfCity()返回公共基本类型(即不只是Object),我们称之为MyBaseType,您可以使用else if这样来提高效率(因为它只执行一个if块,而不是像你在问题中那样执行所有三个块):

if (instance is School)
{
    var result = (School) instance;
    // Do stuff specific to an instance of School
}
else if (instance is Teacher)
{
    var result = (Teacher) instance;
    // Do stuff specific to an instance of Teacher
}
else if (instance is Student)
{
    var result = (Student) instance;
    // Do stuff specific to an instance of Student
}

答案 1 :(得分:0)

理想情况下,您希望这3个类中的每一个都实现一个公共接口,或者从提供GetAcademicDetailsOf函数的基类继承。这样你只需要担心最少的演员。

AcademicDetails results = instance.GetAcademicDetails();

答案 2 :(得分:-1)

用作运营商:https://msdn.microsoft.com/en-us/library/cscsdfbt.aspx

最高效的解决方案是" as"运营商。使用c#进行转换比其他指令使用更多的资源。因此,你投的越少,你就越快。

var instance = GetAcademicDetailsOfCity();
var school = instance as School;
if (school != null)
{
     // do school  specific tasks
}

var teacher = instance as Teacher;
if (teacher != null)
{
     // do teacher  specific tasks
}

var student = instance as Student;
if (student != null)
{
     // do student specific tasks
}