首页 > 解决方案 > 反射无法转换对象

问题描述

我想使用反射来动态填充任何类,但是当这个类具有与其他类一样的属性时,我遇到了问题。在上面的这个例子中,我复制了一部分代码来显示同样的困难。我无法将对象转换为地址。

你能帮助我吗?

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

标签: c#reflectioncastingtype-conversion

解决方案


泛型在编译时解析,而不是在运行时解析。

在这一行

instanceIntermediate = GenerateDataSample(instanceIntermediate); 

instanceIntermediate 是一个Address 对象,但是这里的编译器只知道它是一个对象。所以它调用 GenerateDataSample 它将在这一行中构造一个对象

object tipoInstance = Activator.CreateInstance(typeToWork);

要让 GenerateDataSample 创建对象 classToWork 类型的实例,请使用

object tipoInstance = Activator.CreateInstance(classToWork.GetType());

推荐阅读