我想做的在 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)
{
// tBelow causes: Cannot initialize a by-reference variable with a value
ref sMyStruct s=(t==eMyType.TypeX) ? ref VarMyStructX : ref VarMyStructY;
// Below casues: A ref or out argument must be an assignable variable
ref sMyStruct s=ref ((t==eMyType.TypeX) ? VarMyStructX : VarMyStructY);
// Below 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# 中做到这一点?
我基本上不想将该结构复制到另一个结构,因为不需要。我只想引用正确的变量。
你想要的都是可能的,只是用三元运算符
?:
是不可能的。使用常规 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 变量,您只需以冗长的方式进行即可。