I Want use Reflection to dynamic to populate any class, but when this class has a property as other class I have encountered problem. in this example above I reproduce, a part of code to show same dificult. I Cant convert object to Address.
Can you help me?
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;
}
}
Aucun commentaire:
Enregistrer un commentaire