保持对结构或其他方法的引用来重构此代码?

时间:2012-10-11 18:54:37

标签: c# reference refactoring

我有这段代码:

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 个答案:

答案 0 :(得分: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);
    }
}

答案 1 :(得分:1)

你不能完全删除if但你可以把它拉出循环:

bool isLeftHandSide = true;

if (isLeftHandSide)
   lhs = NewMethod(lhs, txtResult.Text);
else
   rhs = NewMethod(rhs, txtResult.Text);

答案 2 :(得分: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;

答案 3 :(得分: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;