对象类型转换通常有两种情况:
-
一种是当需要转化对象的类型属于转换目标类型或者转换目标类型的派生类型
-
两个对象没有关系,但属性和方法一样。
-
针对第一种情况可以使用as进行对象转换
cs
public class StudentInfo{
public string Name;
public int Age;
public string Course;
}
public class TeacherInfo{
public string Name;
public int Age;
}
public enum Type{
Student;
Teacher;
}
public void Test(Type type,object data){
switch(type){
case Type.Student:
StudentInfo studentInfo = data as StudentInfo;
break;
case Type.Teacher:
TeacherInfo teacherInfo = data as TeacherInfo;
break;
}
}
- 针对第二种情况,可以使用序列化反序列化方法
cs
void Main()
{
TeacherInfo teacher = new TeacherInfo();
teacher.name = "Jane";
teacher.age = 20;
StudentInfo studentInfo = ConvertObject<StudentInfo>(teacher);
studentInfo.name.Dump();
}
public class StudentInfo
{
public string name;
public int age;
}
public class TeacherInfo
{
public string name;
public int age;
}
public static T ConvertObject<T>(object asObject) where T : new()
{
//此方法将object对象转换为json字符
var json = Newtonsoft.Json.JsonConvert.SerializeObject(asObject);
//再将json字符转换为实体对象
var t = Newtonsoft.Json.JsonConvert.DeserializeObject<T>(json);
return t;
}