簡體   English   中英

方法,返回不同數據類型的多個值

[英]Method, returning multiple values of different data types

我試圖返回正則表達式匹配的字符串數組stringArray以及關聯的匹配match_count string_indexmatch_length 如何在方法返回中發送不同數據類型的多個不同值。 我已經讀過一個元組,但是所有示例基本上都顯示了多個值,但它們似乎總是整數而不是混合類型。 我無法在示例中使用它來實現字符串數組和整數。

    string ptrn_coords = @"- Coordinates: \[ ([\-0-9]+), ([\-0-9]+), ([\-0-9]+) \]";

    private void button3_Click(object sender, EventArgs e)
    {
        string[] matches;
        matches = GetMatches(s, ptrn_coords);
    }



    private static string[] GetMatches(string input, string pattern)
    {

        string[] stringArray;
        Match mc = Regex.Match(input, pattern);

        int string_index = 0;
        int match_length = 0;
        int match_count = 0;
        List<String> listTemp = new List<string>();
        while (mc.Success)
        {
            match_count++;
            string_index = mc.Index;
            match_length = mc.Length;               
            listTemp.Add(mc.ToString());

            //MessageBox.Show("Match Text: " + mc.ToString() + " Index: " + string_index + " Length: " + match_length + " Count: " + match_count); // Test Message

            mc = mc.NextMatch();
        }
        stringArray = listTemp.ToArray<String>();
        return stringArray;

    }

不確定要返回的內容,如果要返回stringarray和matchcount等,則可以簡單地定義具有這些屬性的類,然后返回該類的實例。

元組是類型安全的,並且可以安全地返回原始類型和復雜類型的混合。 這是一個例子:

void Main()
{
    var x = GetTuple();
    Console.WriteLine($"{x.Item1} {x.Item2} {x.Item3.GetType().Name}"); // Prints "string 5 MyClass"
}

....

public Tuple<string, int, MyClass> GetTuple()
{
    string myString = "string";
    int myInt = 5;
    MyClass myClass = new MyClass();
    return Tuple.Create(myString,myInt,myClass);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM