如您从标题中所见,我需要将此对象转换为:
object obj = new{
Id = 1,
Name = "Patrick"
};
针对特定的类实例。
为了更加清晰,这里给大家提供一个例子:
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
}
public class Scholar
{
public int UniqueId { get; set; }
public string FullName { get; set; }
}
我有两个类,学生和学者。我无法找到一种合适的方式来编写转换为特定类型的算法。
在我看来,伪代码应该如下所示:
if (obj.CanBeConverted<Student>()) {
//should return this if statement
obj = ConvertToType<Student>(o);
// after this method obj type should change to Student
} else if (obj.CanBeConverted<Scholar>()) {
//at current example wont reach this place
obj = ConvertToType<Scholar>(o);
// after this method obj type should change to Scholar
}
有没有一种编程方式可以实现这个功能?
我在网上搜索并找到了这个例子:https://dev59.com/d2Qn5IYBdhLWcg3wGD5s#17322347
然而,这种解决方案总是尝试将对象或动态类型转换/反序列化为具体对象。
new Student(obj.Id, obj.Name)
是什么意思?或者我完全错过了什么? - pijemcolu