0

首先,如果这个问题被问了一千次,我很抱歉。我读了我的 C# 书,我用谷歌搜索了它,但我似乎找不到我正在寻找的答案,或者我错过了重点。

我对整个装箱/拆箱问题感到非常困惑。假设我有不同类的字段,所有返回类型变量(例如'double'),我希望有一个变量指向这些字段中的任何一个。在普通的旧 CI 中会执行以下操作:

double * newVar;
newVar = &oldVar;
newVar = &anotherVar;
...

我有一个计时器调用一个函数并传递引用变量的值:

ChartPlotData(*newVar);

我寻找指针的原因是因为 newVar 在运行时发生变化,链接到一个事件:

public void checkbox_Clicked(object sender ...)
  if (sender == checkbox1) value = &object1.field1;
  if (sender == checkbox2) value = &object2.field1;

这如何在 C# 中完成?

EDIT1:解释了引用的目的。

EDIT2:做了一些不正确的陈述,删除它们并缩短了问题。

4

4 回答 4

1

You could have a click event, as suggested in your edit, and then use a delegate to select the data to be passed to the control. I'm not sure if that'll meet your performance requirements though.

ChartPlotData(valueSelector());

// ...

Func<double> valueSelector;

protected void Checkbox_Click(object sender /* ... */)
{
    if (sender == checkbox1) valueSelector = () => object1.field1;
    if (sender == checkbox2) valueSelector = () => object2.field1;
    // ...
}

(If you preferred, and if you're able to, you could overload your ChartPlotData method to accept a Func<double> rather than a plain double, and then invoke the selector delegate lazily inside the method rather than at the call site.)

于 2011-01-06T10:06:36.620 回答
0

简单类型和结构在 C# 中属于值类型。除非您提到使用 unsafe 修饰符,否则您无能为力。话虽如此,您的选择是有限的。

  1. 使用对象而不是原始类型。
  2. 使用大小为 1 的数组。
  3. 封装上述任何一种的自定义通用代理类。
  4. ???
于 2011-01-06T00:36:24.193 回答
0

ref您可以使用关键字引用现有的值类型。

public static void ModifyNumber(ref int i)
{
    i += 1;
}

static void Main(string[] args)
{
    int num = 4;
    ModifyNumber(ref num);
    ModifyNumber(ref num);
    ModifyNumber(ref num);
    ModifyNumber(ref num);


    // num now equals 8


}
于 2011-01-06T00:50:18.003 回答
0

我不确定你为什么需要变量的地址。Double 是值类型,存储在堆栈中。要通过引用将其传递给方法,只需使用 C# ref 关键字。
从您提到的案例中,我个人更喜欢这样的事情:

class Program
{
    public class Refferenced<T> where T : struct 
    {
        public T Value { get; set; }
    }

    static void Main(string[] args)
    {
        Refferenced<double> x = new Refferenced<double>();
        Refferenced<double> y = new Refferenced<double>();
        y.Value = 2;
        x = y;
        x.Value = 5;
        Console.WriteLine(x.Value);
        Console.WriteLine(y.Value);
        y.Value = 7;
        Console.WriteLine(x.Value);
        Console.WriteLine(y.Value);

        Console.ReadKey();
    }


它类似于 C# NullAble 类型。

于 2011-01-06T00:51:23.273 回答