Obtain object type in c #

2

Suppose the following code:

public struct Result
{
    public object objectResult
    public Type objectType;
}

Result resultado = CualquierFuncion();

The CualquierFuncion function would be something like this:

public Result CualquierFuncion()
{
   Result result;
   ...
   ...

   result.objectResult = myNewUnknowTypedObject;
   result.objectType = myNewUnknowTypedObject.GetType();
   return result
}

What I want to do (or know if it is possible to do and how) is something like the following:

var xxx = (result.objectType) result.objectResult; 

I know that the direct typecast will not work, but is it possible to do this in any way other than by comparing the saved type value with the different expected types?

    
asked by RaptoR 26.05.2017 в 15:56
source

4 answers

1

Use dynamic and Convert.ChangeType

public class Test
{
    public void Saludo()
    {
        Console.Write("hola mundo");
    }
}

static void Main(string[] args)
    {
        Test prueba = new Test();
        Result objeto = new Result
        {
            objectResult = prueba,
            objectType = prueba.GetType()
        };

        dynamic miTest = Convert.ChangeType(objeto.objectResult, objeto.objectType);
        miTest.Saludo();

        Console.ReadLine();
    }
    
answered by 04.09.2017 в 18:50
0

If you definitely need to do it that way, you could try the following line of code:

var xxx = Convert.ChangeType(result.objectResult, Type.GetType(result.objectType));
    
answered by 04.09.2017 в 18:35
-1

How many options of objects could you have? what you could do is make the type query and according to that you make an explicit conversion

if (result.objectResult.GetType().Equals(typeof(AlgunaClaseQuePuedaSer)))
{
    var xxx = (AlgunaClaseQuePuedaSer) result.objectResult; 
}
else if (result.objectResult.GetType().Equals(typeof(OtraClaseQuePuedaSer)))
{
    var xxx = (OtraClaseQuePuedaSer) result.objectResult; 
}
    
answered by 26.05.2017 в 20:47
-2

I would do it in the following way:

public T CualquierFuncion<T>()
{
    T result;
    ...
    // Aquí 'result' debería llenarse 
    ...   

return result
}

In such a way that xxx is going to be of the type that is returned in the function

var xxx = CualquierFuncion();
    
answered by 04.09.2017 в 16:38