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

时间:2018-04-25 12:04:06

标签: c# object dynamic reflection

正如您从标题中看到的,我需要转换此对象:

    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://stackoverflow.com/a/17322347/8607147

但是,此解决方案始终尝试将对象或动态类型转换/反序列化为具体对象。

1 个答案:

答案 0 :(得分:1)

您可以使用Json.Net SchemaJson.Net来完成,请查看我是如何做到的:

  class Program
  {
    static void Main(string[] args)
    {
      var o = new
      {
        Id = 1,
        Name = "Patrick",
        Courses = new[] { new { Id = 1, Name = "C#" } }
      };

      Student student = null;
      Scholar scholar = null;

      if (o.CanBeConverted<Student>())
        student = o.ConvertToType<Student>();
      else if (o.CanBeConverted<Scholar>())
        scholar = o.ConvertToType<Scholar>();

      System.Console.WriteLine(student?.ToString());
      System.Console.WriteLine(scholar?.ToString());

      System.Console.ReadKey();
    }
  }

  public static class ObjectExtensions
  {
    public static bool CanBeConverted<T>(this object value) where T : class
    {
      var jsonData = JsonConvert.SerializeObject(value);
      var generator = new JSchemaGenerator();
      var parsedSchema = generator.Generate(typeof(T));
      var jObject = JObject.Parse(jsonData);

      return jObject.IsValid(parsedSchema);
    }

    public static T ConvertToType<T>(this object value) where T : class
    {
      var jsonData = JsonConvert.SerializeObject(value);
      return JsonConvert.DeserializeObject<T>(jsonData);
    }
  }

  public class Student
  {
    public int Id { get; set; }
    public string Name { get; set; }
    public Courses[] Courses { get; set; }

    public override string ToString()
    {
      return $"{Id} - {Name} - Courses: {(Courses != null ? String.Join(",", Courses.Select(a => a.ToString())) : String.Empty)}";
    }
  }

  public class Courses
  {
    public int Id { get; set; }
    public string Name { get; set; }

    public override string ToString()
    {
      return $"{Id} - {Name}";
    }
  }

  public class Scholar
  {
    public int UniqueId { get; set; }
    public string FullName { get; set; }

    public override string ToString()
    {
      return $"{UniqueId} - {FullName}";
    }
  }

解决方案基本上是从您想要的对象生成一个JSON Schema,并检查新的数据队列是否适合这个shema。