1. 程式人生 > >C# 元組、匿名物件、ref&out

C# 元組、匿名物件、ref&out

元組

private (int number,int newNumber) CaculateByTuple(int number)
{
    return (number: number,
        newNumber: number * number);
}

private List<(int number, int newNumber)> CaculateByTuple(List numbers)
{
    return numbers.AsEnumerable().Select(
        x =>
        {
            return (number: x,
            newNumber: x * x);
        })
        .ToList();
}

匿名物件

private dynamic CaculateByDynamic(int number)
{
    return new
    {
        number = number,
        newNumber = number * number
    };
}

ref&out

ref
private int CaculateByRef(ref int number)
{
    //對於ref
    //在進入方法CaculateByRef之前,number必須賦值
    //在方法CaculateByRef裡面,number可以不進行修改
    number = 2;
    return number * number;
}
out
private int CaculateByOut(out int number)
{
    //對於ref
    //在進入方法CaculateByOut之前,number不必賦值
    //在方法CaculateByOut裡面,number必須進行賦值
    number = 3;
    return number * number;
}

ref&out的壞處在於:
查詢number值的引用時,只能查詢到ref&out這個方法名上面,對於IDE來說,方法修改了一個變數值,而不是修改了number
在開發過程中的查詢檢索會遇到困難,如下所示:
1
2

測試方法

public void Test()
{
    //ref
    int number = 1;
    int newNumber=CaculateByRef(ref number);

    //out
    newNumber = CaculateByOut(out number);

    //元組
    var returnValues = CaculateByTuple(number);
    number = returnValues.number;
    newNumber = returnValues.newNumber;

    //匿名物件
    var returnValues2 = CaculateByDynamic(number);
    number = returnValues2.number;
    newNumber = returnValues2.newNumber;

    //元組2
    List numbers = new List();
    numbers.Add(1);
    numbers.Add(2);
    numbers.Add(3);
    var returnValues3 = CaculateByTuple(numbers);
}

示例