gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 22:45:47 25 4
gpt4 key购买 nike

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

    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; }

}

我有两个类(class)学生学者。我想不出一种方法来正确编写转换为特定类型的算法。

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

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

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

最佳答案

您可以使用 Json.Net Schema 来完成和 Json.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,并检查新数据是否符合这个 schema。

关于c# - 在 .NET C# 中将动态对象转换为具体对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50021869/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com