简体   繁体   中英

C# Cannot convert from 'out string' to 'out dynamic'

I have a function structurally similar to this one:

void Foo(dynamic arg1, dynamic arg2, out dynamic result) {
    result = arg1 + arg2;
}

I'm using dynamic since this function should generically handle any type I throw at it.
But if I try to call it like so:

string Bar = null;
...
Foo("a", "b", out this.Bar);

I get an error message; I seemingly can't pass my pre-defined string Bar to the function ( Cannot convert from 'out string' to 'out dynamic' ).
However, when I remove the 'out' keyword from the type declaration and my function call, everything works completely fine (I'm mentioning this to prove the point that everything else works perfectly fine).
I do not understand why the out modifier changes the whole situation, and dynamic suddenly can't be cast to a string, like I would be able to do it by implicitly assigning it as stated in the docs .
I'd gladly appreciate any help, there seemingly aren't a lot of people out there passing strings to a function expecting a dynamic with the out modifier...

I get an error message; I seemingly can't pass my pre-defined string Bar to the function (Cannot convert from 'out string' to 'out dynamic').

The reason for this error is because it couldn't be inferred. To get around this you could however use a generic that satisfies this.

 void Foo<T>(dynamic arg1, dynamic arg2, out T result)

All works as expected from your example...

 Foo("a", "b", out this.Bar); // "ab"
 Foo(1, 123, out int test); // test == 124

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