1

我有这个代码:

BigInteger lhs = new BigInteger(0);
BigInteger rhs = new BigInteger(0);

bool isLeftHandSide = true;

for (int i = 0; i < txtResult.Text.Length; i++)
{
    char currentCharacter = txtResult.Text[i];

    if (char.IsNumber(currentCharacter))
    {
        char currentCharacter = txtResult.Text[i];

        if (isLeftHandSide)
        {
            lhs += (int)char.GetNumericValue(currentCharacter);
        }
        else
        {
            rhs += (int)char.GetNumericValue(currentCharacter);
        }
    }
}

我想知道是否有一种方法可以存储对当前端的引用,以便我可以直接操作该变量并摆脱 if 和 else 语句。我希望能够在不使用不安全代码上下文的情况下做到这一点。

像替换这个:

if (isLeftHandSide)
{
    lhs += (int)char.GetNumericValue(currentCharacter);
}
else
{
    rhs += (int)char.GetNumericValue(currentCharacter);
}

有了这个:

currentSide += (int)char.GetNumericValue(currentCharacter);

currentSide 是对 lhs 或 rhs 的引用。因为它们是结构,所以我不确定如何保留对它的引用,而不仅仅是复制数据。

谢谢。

4

4 回答 4

3

您所需要的只是一个包装类来添加一个额外的间接层。(我发现这个类有时很有用,我把它作为一个实用类保留。)

public class Wrapper<T>
{
    public T Value { get; set; }
}

然后使用它:

BigInteger lhs = new BigInteger(0);
BigInteger rhs = new BigInteger(0);
Wrapper<BigInteger> currentSide = new Wrapper<BigInteger>();

currentSide.Value = lhs;

for (int i = 0; i < txtResult.Text.Length; i++)
{
    char currentCharacter = txtResult.Text[i];

    if (char.IsNumber(currentCharacter))
    {
        currentSide.Value += (int)char.GetNumericValue(currentCharacter);
    }
}
于 2012-10-11T19:30:47.823 回答
1

您可以在 lambda 中捕获所需的变量,如下所示:

Action<int> addToCurrentSide;

BigInteger lhs = new BigInteger(0);
BigInteger rhs = new BigInteger(0);

addToCurrentSide = x => lhs += x;

for (int i = 0; i < txtResult.Text.Length; i++)
{
    char currentCharacter = txtResult.Text[i];

    if (char.IsNumber(currentCharacter))
    {
        char currentCharacter = txtResult.Text[i];

        addToCurrentSide((int)char.GetNumericValue(currentCharacter));
    }
}

然后换边,你只需重新分配addToCurrentSide

addToCurrentSide = x => rhs += x;
于 2012-10-11T19:14:50.587 回答
1

您不能完全删除,if但可以将其拉出循环:

bool isLeftHandSide = true;

if (isLeftHandSide)
   lhs = NewMethod(lhs, txtResult.Text);
else
   rhs = NewMethod(rhs, txtResult.Text);
于 2012-10-11T19:14:08.277 回答
1

你可以这样做,

var isLeftHandSide = true;
var currentSide = new BigInteger(0);

for (int i = 0; i < txtResult.Text.Length; i++)
{
    char currentCharacter = txtResult.Text[i];
    if (char.IsNumber(currentCharacter))
        currentSide += (int)char.GetNumericValue(currentCharacter);
}

if (isLeftHandSide)
    // lhs = currentSide;
else
    // rhs = currentSide;
于 2012-10-11T19:19:50.837 回答