문제

매개 변수가 될 수있는 메소드를 갖고 싶습니다. Int32 또는 Single:

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

C#은 사용할 때 객체의 전문화를 전달할 수 없기 때문에 out 또는 ref, 내가 찾은 솔루션은 변수를 유형의 변수에 할당한다고 주장했다. object 충분할 것입니다 :

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

작동하지 않았습니다. 내가 본 Microsoft 문서에 따르면 o 포인터가되어야합니다 s. 내가 보았던 소스는 비-프리맨 유형을 할당하는 것이 참조를 생성하고 new 사례.

내가 통과 할 수있는 방법을 가질 수 있습니까? Single 또는 Int32 또는 전문화 인 기타 유형 object?

도움이 되었습니까?

해결책

메소드 과부하 :

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

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

다른 팁

불행히도, 당신은 운이 좋지 않습니다. 두 가지 방법을 사용하는 것이 좋습니다.

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

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

"매개 변수가 int32 또는 단일 일 수있는 메소드를 갖고 싶습니다."

a를 사용하는 것은 어떻습니까 일반적인 방법 대신에?

NB : 현재 버전의 C#에서는 int, float와 같은 특정 유형이 아닌 구조적으로 허용 유형을 구조화 할 수 있습니다.

객체의 값을 복싱하는 대신 기능을 과부하시킬 수 있습니다.

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

방법 내부의 논쟁으로하는 일은 물론 달성하려는 것에 달려 있습니다.

아마도 Ash의 접근 방식을 사용하고 다음 줄을 따라 일반적인 구현을 할 것입니다.

    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();
    }
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top