简体   繁体   中英

Delegates with return type multicast gives unexpected result

I was trying to learn delegate multicasting and wrote this sample program :

delegate string strDelegate(string str);

class strOps
{
    public static string reverseString(string str)
    {
        string temp = string.Empty;
        for(int i=str.Length -1 ; i>=0 ; i--)
        {
            temp += str[i];
        }

        return temp;

    }

    public string removeSpaces(string str)
    {
        string temp = string.Empty;
        for (int i = 0; i < str.Length; i++)
        {
            if (str[i] != ' ')
                temp += str[i];
        }

        return temp;
    }
}

// calling the code in main method
string str = "This is a sample string";
strOps obj = new strOps();
strDelegate delRef = obj.removeSpaces;
delRef += strOps.reverseString;

Console.WriteLine("the result of passing This is a sample string  \n {0}", delRef(str));

I expected it to return the reversed string without spaces , instead it ONLY reverses string and gives this output : gnirts elpmas a si sihT

Can anybody please point me in the right direction to understand this. Any help will be appreciated. Thanks.

A combined delegate will only return the result of the last invoked method . From the documentation :

If the delegate has a return value and/or out parameters, it returns the return value and parameters of the last method invoked

The multicast delegate will still invoke both methods assigned to it . If you change your methods to print the value before returning it, you'll see it clearly:

void Main()
{
    string str = "This is a sample string";
    strOps obj = new strOps();
    strDelegate delRef = obj.removeSpaces;
    delRef += strOps.reverseString;

    delRef(str);
}

delegate string strDelegate(string str); 
class strOps
{
    public static string reverseString(string str)
    {
        string temp = string.Empty;
        for(int i=str.Length -1 ; i>=0 ; i--)
        {
            temp += str[i];
        }
        Console.WriteLine("Output from ReverseString: {0}", temp);
        return temp;

    }

    public string removeSpaces(string str)
    {
        string temp = string.Empty;
        for (int i = 0; i < str.Length; i++)
        {
            if (str[i] != ' ')
                temp += str[i];
        }
        Console.WriteLine("Output from RemoveSpaces: {0}", temp);
        return temp;
    }
}

Outputs:

Output from RemoveSpaces: Thisisasamplestring
Output from ReverseString: gnirts elpmas a si sihT

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM