Why do partial methods have to be void?
I am currently learning C# with the bo开发者_如何学JAVAok called Beginning Visual C# 2010 and I am in the chapter that discusses different aspects and characteristics of partial methods and classes.
To quote the book:
Consider at this point why partial methods can’t have a return type. If you can answer that to your own satisfaction, you can be sure that you fully understand this topic — so that is left as an exercise for you."
This is where I get stuck. The only reason that I can think of is that when the method's return value is assigned to something in the code, it would generate an error if there is no definition implemented for the partial method.
Can someone clear this topic for me please?
Because calls to them can't be eliminated from the calling code in case they are not implemented without breaking it.
Example:
partial void foo();
partial int bar();
Calling code:
...
foo(); // successfully removed if foo isn't implemented
int x = bar() * 2; // what to do here?
Console.WriteLine(x);
Note that starting from C# 9.0 from 2020, partial
methods are no longer required to return void
. Of course, this also means that the C# compiler must be able to guarantee that another "part" is actually present (possibly generated by some magic) that has the implementation of the method.
See partial method (C# Reference).
精彩评论