Pass class type dynamically on a method in c #

3

Starting from:

Person model

  public class Persona
{
    [BsonRepresentation(BsonType.ObjectId)]
    public string Id { get; set; }
    [Required]
    public string Nombre { get; set; }
    [Required]
}

Buzon Model

public class Buzon
{

    [BsonRepresentation(BsonType.ObjectId)]
    public string Id { get; set; }
    public int NumTicket { get; set; }
    public string Titulo { get; set; }
}

Method that makes a query to Mongo

  public string GetCollectionExcludeFields(string nameCollection, string[] campos)
    {
        String camposFormato = "";
        for (int i = 0; i <= campos.Length-1; i++)
        {
            if (i == campos.Length - 1)
            {
                camposFormato += campos[i] + ":1";
            }
            else
            {
                camposFormato += campos[i] + ":1,";
            }
        }
//Aquí, remplazar ese tipo estatico Project<Persona> a dinámico
        return db.GetCollection<BsonDocument>(nameCollection).Find(x => true).Project<Persona>("{"+ camposFormato + "}").ToList().ToJson();


    }

My question: Is it possible to pass the "Person" class dynamically ?, something like:

 public string GetCollectionExcludeFields(string nameCollection, string[] campos,tipoclase clase)
{
    String camposFormato = "";
    for (int i = 0; i <= campos.Length-1; i++)
    {
        if (i == campos.Length - 1)
        {
            camposFormato += campos[i] + ":1";
        }
        else
        {
            camposFormato += campos[i] + ":1,";
        }
    }
//Aquí, remplazar ese tipo estatico Project<Persona> a dinámico Project<clase>
    return db.GetCollection<BsonDocument>(nameCollection).Find(x => true).Project<clase>("{"+ camposFormato + "}").ToList().ToJson();


}
    
asked by harriroot 23.10.2017 в 17:42
source

1 answer

2

According to this programming guide what you need to do is define your method GetCollectionExcludeFields with a generic type specification (the <T> next to the name of the method):

public string GetCollectionExcludeFields<T>(string nameCollection, string[] campos)
{
    String camposFormato = "";
    for (int i = 0; i <= campos.Length-1; i++)
    {
        if (i == campos.Length - 1)
        {
            camposFormato += campos[i] + ":1";
        }
        else
        {
            camposFormato += campos[i] + ":1,";
        }
    }

    return db.GetCollection<BsonDocument>(nameCollection).Find(x =>true)
        .Project<T>("{"+ camposFormato + "}").ToList().ToJson();
}

And you execute it like this:

GetCollectionExcludeFields<Persona>(...);
    
answered by 23.10.2017 / 18:05
source