Domanda

Vorrei avere un metodo in cui il parametro potrebbe essere Int32 o Single :

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

Dato che C # non mi consente di passare una specializzazione dell'oggetto quando uso out o ref , la soluzione che ho trovato affermava che l'assegnazione della variabile a una variabile del tipo oggetto sarebbe sufficiente:

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

Non ha funzionato. Secondo la documentazione Microsoft che ho esaminato, o dovrebbe essere un puntatore a s . Le fonti che ho visto affermano che l'assegnazione di tipi non primitivi genera un riferimento e non un'istanza new .

È possibile avere un metodo in cui posso passare Single o Int32 o qualsiasi altro tipo che è una specializzazione di oggetto ?

È stato utile?

Soluzione

Sovraccarico del metodo:

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

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

Altri suggerimenti

Sfortunatamente, sei sfortunato. Farai meglio ad usare due metodi:

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

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

" Vorrei avere un metodo in cui il parametro potrebbe essere Int32 o Single "

Che ne dici di usare un Metodo generico invece?

NB: Nell'attuale versione di C # puoi essere in grado di vincolare solo i tipi consentiti per strutturare tipi non specifici come int, float.

Invece di racchiudere il valore in un oggetto, è possibile sovraccaricare la funzione:

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);
        }
    }
}

Ciò che fai con l'argomento all'interno dei metodi dipende ovviamente da ciò che stai cercando di realizzare.

Probabilmente userei l'approccio di Ash e andrei con un'implementazione generica seguendo le seguenti linee:

    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();
    }
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top