mardi 1 mars 2016

How do I use reflection to check an interface property?

I have an interface:

public interface IHaveTheStuff<T>
{
    T Stuff { get; set; }
}

I can implement it like this:

public class StringGuy: IHaveTheStuff<string>
{
    string Stuff { get; set; }
}

public class IntGuy: IHaveTheStuff<int>
{
    int Stuff { get; set; }
}

I have a different class:

public class Customer
{
    public string StringStuff { get; set; }
    public int IntStuff { get; set; }
}

And finally, I have this method:

public Customer SetUpCustomer<T>(IHaveTheStuff<T> guy)
{
    var customer = new Customer();
    // ah, that's the stuff

    return customer;
}

What I want to do: when the SetUpCustomer method gets called, I want to use reflection to check the type of the TheStuff property in the passed guy parameter. Based on that, I want to set the property in customer with the same property as TheStuff in guy.

For example, if a StringGuy gets passed to SetUpCustomer, it should return a Customer object with the StringStuff property set. How do I do this?





Aucun commentaire:

Enregistrer un commentaire