Pregunta

Me gustaría tener un método donde el parámetro podría ser Int32 o Single :

void myMethod( ref object x )
{
     //...CodeHere
}

Dado que C # no me permite pasar una especialización de objeto cuando uso out o ref , la solución que encontré afirmó que asignar la variable a una variable del tipo object sería suficiente:

Single s = 1.0F;
object o = s;
myMethod( ref o );

Eso no funcionó. De acuerdo con la documentación de Microsoft que miré, o debería ser un puntero a s . Las fuentes que analicé indican que la asignación de tipos no primitivos genera una referencia y no una instancia de new .

¿Es posible tener un método en el que pueda pasar Single o Int32 o cualquier otro tipo que sea una especialización de object ?

¿Fue útil?

Solución

Sobrecarga el método:

void myMethod( ref int x )
{
    //...
}

void myMethod(ref single x)
{
    //...
}

Otros consejos

Desafortunadamente, no tienes suerte. Estará mejor usando dos métodos:

void MyMethod(ref float x)
{
  //....
}

void MyMethod(ref int x)
{
  //....
}

" Me gustaría tener un método donde el parámetro podría ser Int32 o Single "

¿Qué tal usar un Método genérico en su lugar?

NB: en la versión actual de C # solo puede restringir los tipos permitidos para estructurar tipos no específicos como int, float.

En lugar de encuadrar el valor en un objeto, podría sobrecargar la función:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
        }

        static int test = 0;

        static void MyMethod(int arg)
        {
            test += arg;
        }

        static void MyMethod(ref int arg)
        {
            test += arg;
        }

        static void MyMethod(Single arg)
        {
            test += Convert.ToInt32(arg);
        }

        static void MyMethod(ref Single arg)
        {
            test += Convert.ToInt32(arg);
        }
    }
}

Lo que haces con el argumento dentro de los métodos depende de lo que intentas lograr, por supuesto.

Probablemente usaría el enfoque de Ash e iría con una implementación genérica en las siguientes líneas:

    static void myMethod<T>(ref T value) where T : struct, IConvertible, IComparable<T>, IEquatable<T>
    {
        value = (T)Convert.ChangeType(value.ToSingle(CultureInfo.CurrentCulture) * 2.0, typeof(T));
    }

    static void Main(string[] args)
    {
        int data1 = 5;

        myMethod(ref data1);
        if (data1 != 10)
            throw new InvalidOperationException();

        Single data2 = 1.5f;

        myMethod(ref data2);
        if (data2 != 3)
            throw new InvalidOperationException();
    }
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top