c# - 反射无法转换对象
问题描述
我想使用反射来动态填充任何类,但是当这个类具有与其他类一样的属性时,我遇到了问题。在上面的这个例子中,我复制了一部分代码来显示同样的困难。我无法将对象转换为地址。
你能帮助我吗?
public class Destinatary
{
public string DetinataryID { get; set; }
public string Name { get; set; }
public Address Address { get; set; }
}
public class Address
{
public string Place { get; set; }
public string PostalCode { get; set; }
}
class Program
{
static void Main(string[] args)
{
Destinatary destinataryTest = new Destinatary();
Type type = typeof(Destinatary);
destinataryTest = GenerateDataSample(destinataryTest);
Console.WriteLine($"Name: {destinataryTest.Name}");
Console.WriteLine($"Place: {destinataryTest.Address.PostalCode}");
Console.WriteLine($"City: {destinataryTest.Address.City.Name}");
Console.ReadLine();
}
private static T GenerateDataSample<T>(T classToWork)
{
Type typeToWork = typeof(T);
object tipoInstance = Activator.CreateInstance(typeToWork);
foreach (var classProperty in typeToWork.GetProperties())
{
if (classProperty.PropertyType.FullName.StartsWith("System."))
{
var propertyVal = RandomString(10,false );
classProperty.SetValue(tipoInstance, propertyVal, null);
}
else
{
var instanceIntermediate = Activator.CreateInstance(classProperty.PropertyType);
instanceIntermediate = GenerateDataSample(instanceIntermediate);
classProperty.SetValue(tipoInstance, instanceIntermediate, null); //here there is a probleman (Cant convert Object to Address)
}
}
return (T)tipoInstance;
}
}
解决方案
泛型在编译时解析,而不是在运行时解析。
在这一行
instanceIntermediate = GenerateDataSample(instanceIntermediate);
instanceIntermediate 是一个Address 对象,但是这里的编译器只知道它是一个对象。所以它调用 GenerateDataSample 它将在这一行中构造一个对象
object tipoInstance = Activator.CreateInstance(typeToWork);
要让 GenerateDataSample 创建对象 classToWork 类型的实例,请使用
object tipoInstance = Activator.CreateInstance(classToWork.GetType());
推荐阅读
- java - Web 应用程序的通用加密 - 如何?
- python - “itk::ERROR: GeodesicActiveContourLevelSetImageFilter(000002189D4F4460): 输入不占用相同的物理空间!”
- javascript - 如何为所有幻灯片指定相同的过渡速度,而不管它们的宽度如何?
- javascript - 如何在我的自定义网站中添加 CSS 和 HTML 编辑器?
- javascript - Async Await & Promise 解释
- reactjs - React Native:One Signal 推送通知设置状态
- amazon-dynamodb - 如何在 aws-dynamodb 中通过 DateTimeStamp desc limit 10 实现`select * from InternalProductionDb order
- php - 如何在 phpunit 中包含 inc 文件配置
- vue.js - Vuejs 这是实现服务的好方法吗?
- assembly - 什么是内部函数的 SSE2 程序集等效项?