正如你从标题中看到的,我需要转换这个对象:
object obj = new{
Id = 1,
Name = "Patrick"
};
Run Code Online (Sandbox Code Playgroud)
到特定的类实例。
为了更清楚,这里有一个例子给你们:
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; }
}
Run Code Online (Sandbox Code Playgroud)
我有两个班级Student和Scholar。我无法找到一种正确编写转换为特定类型的算法的方法。
在我看来,伪代码应该是这样的:
if (obj.CanBeConverted<Student>()) {
//should return this if statement
obj = ConvertToType<Student>(o);
// after this method obj type should change to Student
} …Run Code Online (Sandbox Code Playgroud)