如何有条件地将局部变量引用分配给c#中的另一个变量? [重复]

问题描述 投票:0回答:1

我想做的在 c/c++ 中看起来像这样:

bool MyFunc(eMyType t)
{
  sMyStruct* s=(t==TypeX) ? &VarMyStructX : &VarMyStructY;

  if (s->dataneeded>0) 
    return true;

  return false;
}

但在 C# 中,所有分配似乎都不起作用:

public bool MyFunct(in eMyType t)
{
  // This causes: Cannot initialize a by-reference variable with a value
  ref sMyStruct s=(t==eMyType.TypeX) ? ref VarMyStructX : ref VarMyStructY;
  // This causes: A ref or out argument must be an assignable variable
  ref sMyStruct s=ref ((t==eMyType.TypeX) ? VarMyStructX : VarMyStructY);
  // This causes: You can only take the address of an unfixed expression inside of a fixed statement initializer
  sMyStruct* s=(t==TypeX) ? &VarMyStructX : &VarMyStructY;

  if (s.dataneeded > 0)
    return true;

  return false;
}

如何在 C# 中做到这一点?

我基本上不想将该结构复制到另一个结构,因为不需要。我只想引用正确的变量。

c# reference
1个回答
0
投票

你想要的都是可能的,只是用三元运算符

?:
是不可能的。使用常规 IF..ELSE 语句。

这是我在 ideone.com 快速创建的示例:

using System;

public struct Point
{
    public int X;
    public int Y;
}

public class Test
{
    public static void Main()
    {
        Func<Point, string> dp = x => $"({x.X}, {x.Y})";
        Point p0 = new Point();
        Point p1 = new Point() { X = 1, Y = 2 };
        Point p2 = new Point() { X = 3, Y = 4 };
        string decider = null;
        do
        {
            decider = Console.ReadLine();
            ref Point p = ref p0;
            if (decider == "1")
            {
                p = ref p1;
            }
            else
            {
                p = ref p2;
            }
            Console.WriteLine(dp(p));
        } while (!String.IsNullOrWhiteSpace(decider));
    }
}

完全有可能重新分配 ref 变量,您只需以冗长的方式进行即可。

© www.soinside.com 2019 - 2024. All rights reserved.