0

我有DataContract定义的 WCF 和其他DataContract一些扩展它的 WCF。所以它的原始形式看起来像这样:

    [DataContract(Name = "FacilityPerson"]
    [KnownType(typeof(Student))]
    [KnownType(typeof(Teacher))]
    public class Person
    {
        [DataMember(IsRequired=true)]
        public string FirstName { get; set; }
        [DataMember]
        public string LastName { get; set; }
        [DataMember]
        public DateTime? DOB { get; set; }   

    }

    [DataContract]
    public class Student
    {
        [DataMember(IsRequired=true)]
        public int StudentID { get; set; }

    }

[DataContract]
public class Teacher
{
    [DataMember(IsRequired=true)]
    public int StaffID { get; set; }

}

我有一个ServieContract只有一个操作,看起来像这样:

[OperationContract(Name = "ReportNewPerson")]
void ReportNewTeacherOrStudent(Person person);

我的问题是当我实现它时,我无法访问父对象的子属性。

public class UniversityService : IUniversityServiceContract  
{

        void ReportNewTeacherOrStudent(Person person)
        {
             if(person.GetType().FullName == "Student")
             {
                     //here I have a parent object so I cannot getStudentId which is a child property           
                     Console.Writeline(person.StudentId);

             }

        }
}

我应该在这里做什么?

4

2 回答 2

3

不要从名称上比较类型;相反,请使用演员表或as运算符来做到这一点:

public class UniversityService : IUniversityServiceContract  
{
    public void ReportNewTeacherOrStudent(Person person)
    {
        Student student = person as Student;
        if (student != null)
        {
            Console.Writeline(student.StudentId);
        }
    }
}
于 2012-08-30T23:18:09.367 回答
1

检查卡洛斯菲盖拉的答案。他是对的。

您还需要为您的TeacherStudent类添加继承:

[DataContract]
public class Student: Person
{
    ...
}

[DataContract]
public class Teacher: Person
{
   ...    
}

更新:是的,您必须在父项和子项中指定属性。

于 2012-08-31T01:46:13.953 回答