jeudi 26 février 2015

Creating objects dynamically from Interface or assembly C#

Lets say I have some interface that looks like the below



public interface IPerson
{
Person GetPerson(string name);
Person SetPerson(Person p);
}


And my person object has some nested objects and maybe it inherits from a base class.



public class Person : SomeBaseClass
{
public Name fullName {get;set;}
// some other stuff
}


Now lets say all the above gets compiled to an assembly (dll). Is it possible to instantiate the Person Object on the fly using reflection?



void Main()
{
Type type = typeof(IPerson);
var instance = Activator.CreateInstace(t);
// can't access properties of Person from instance.. :(
// I wan't to populate all the properties of the object on the fly
// but can't
}


Basically I want to reference the dll or load the assembly dynamically iterate over all the objects in said assembly, create the objects and populate their properties, and finally do something with those objects and their properties. Is this possible? Seems I only have access to Person.Name when I make a static cast.



var oops = (Person)instance; // now I can access. but I dont want to have to cast!





Aucun commentaire:

Enregistrer un commentaire