小编And*_*ter的帖子

将动态对象转换为 .NET C# 中的具体对象

正如你从标题中看到的,我需要转换这个对象:

    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)

我有两个班级StudentScholar。我无法找到一种正确编写转换为特定类型的算法的方法。

在我看来,伪代码应该是这样的:

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)

c# reflection dynamic object

4
推荐指数
1
解决办法
5783
查看次数

标签 统计

c# ×1

dynamic ×1

object ×1

reflection ×1