【问题标题】:C# passing Single as referenceC# 传递 Single 作为参考
【发布时间】:2009-09-14 13:56:29
【问题描述】:

我想要一个参数可以是Int32Single的方法:

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

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

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

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

是否有可能有一种方法可以传递SingleInt32object 的任何其他类型?

【问题讨论】:

  • 您误读了摆在您面前的任何拳击文件。它为原始值的副本生成了一个装箱实例。

标签: c# pass-by-reference


【解决方案1】:

重载方法:

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

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

【讨论】:

  • 我对这个问题的第一个解决方法就是这样,但我认为这应该是另一种方式。这个问题似乎是 Single 和相关的特定问题。复杂类不受此限制。无论如何,如果没有其他解决方案出现,我会使用您的建议。谢谢
  • Flavio:之所以不能按照您认为的方式工作,是因为整数和浮点数是值类型,而对象是引用类型。我建议您阅读差异。这是一个不错的开始 (albahari.com/valuevsreftypes.aspx),但我建议您花一两个小时在 Google 上搜索该主题。
【解决方案2】:

很遗憾,你运气不好。你最好使用两种方法:

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

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

【讨论】:

  • 其实,Joel 领先我 3 秒。 :)
【解决方案3】:

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

改用Generic method 怎么样?

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

【讨论】:

  • 您不能将泛型参数限制为只有intfloat。您可以得到的最接近的方法是将其限制为struct,这将允许许多其他类型溜进来。
【解决方案4】:

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

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

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

【讨论】:

    【解决方案5】:

    我可能会使用 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();
        }
    

    【讨论】:

      猜你喜欢
      • 2023-03-13
      • 1970-01-01
      • 1970-01-01
      • 2011-12-15
      • 2016-04-11
      • 2014-02-10
      • 2010-12-12
      • 2019-12-28
      • 2014-03-05
      相关资源
      最近更新 更多