0

我想要一个参数可以是Int32或的方法Single

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

由于 C# 不允许我在使用outor时传递对象的特化ref,我发现的解决方案声称将变量分配给该类型的变量object就足够了:

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

那没有用。根据我查看的 Microsoft 文档,o应该是指向s. 我查看的资料表明,分配非原始类型会生成引用而不是new实例。

是否有可能有一个我可以通过的方法SingleInt32任何其他类型的专业化object

4

5 回答 5

9

重载方法:

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

void myMethod(ref single x)
{
    //...
}
于 2009-09-14T13:59:06.920 回答
1

不幸的是,你运气不好。使用两种方法会更好:

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

void MyMethod(ref int x)
{
  //....
}
于 2009-09-14T13:59:10.273 回答
1

“我想要一个参数可以是 Int32 或 Single 的方法”

改用通用方法怎么样?

注意:在当前版本的 C# 中,您只能将允许的类型限制为 struct 而不是特定类型,例如 int、float。

于 2009-09-14T14:00:09.027 回答
0

我可能会使用 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();
    }
于 2009-09-14T15:43:34.773 回答
0

您可以重载函数,而不是将值装箱到对象中:

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

当然,你对方法中的参数做什么取决于你想要完成的事情。

于 2009-09-14T14:03:48.597 回答