vendredi 12 mai 2017

Creating generic method to construct and return generic objects?

I want to create a method that will return a Response<> object and set the generic properties based on the type of the object passed in as a parameter. General code example below and additional considerations at the bottom of the post.

public class Response<T>
{
  public string ResponseCode { get; get; }
  public T Object { get; set;}
  public List<T> Objects { get; set; }

  public Response()
  {

  }
}

public class ChildrenResponses
{
  public ChildrenResponses() // constructor
  {

  }

  // some properties
}

public class AdultResponses
{
  public AdultResponses() // constructor
  {

  }

  // some properties
}

public Response<T> GetSpecificResponseType<T>(T genericType)
{
  // ... some logic to instantiate a Response<> object using the parameter type passed into the method.

  // ... some logic to set the generic properties of Response<> object based on the parameter type passed into the method.

  // return object
}

  1. I'm new to C# generics/reflection :)
  2. Being as the Response/ChildrenResponse/AdultResponse classes existed in this code base before I began using it, I'd like to avoid changing those classes.
  3. I've attempted multiple methods to accomplish this task, but none of them worked and providing them in this post would likely just add confusion. Instead, I provided a base method with the general idea I was working with.

An example of how I'd like to call the method:

Response<ChildrenResponses> result = GetSpecificResponseType<ChildrenResponses>("ChildrenResponses");

This method will then return the Response< ChildrenResponses > object with the Object property set to new ChildrenResponses() and Objects set to new List< ChildrenResponses >(). No properties within the ChildrenResponses need to be established - just the instantiating the object is enough.





Aucun commentaire:

Enregistrer un commentaire