问题
I never liked implicit operators (prefer extension methods) because it is hard to see visually when that cast/conversion happens in the code.
Imagine if you have example like below:
public static implicit operator Deal(string dealAsXml)
{
//convert the xml into Deal object
}
Above implicit operator helps you to cast/convert deal in Xml format into Deal Object.
Usually when you right click on a method, you can use "Find Usages" (or Alt+F7) on it, which is quite helpful, is there anything similar for implicit operators ?
I think that's another reason to use the Extensions methods where possible.
回答1:
Maybe something like Resharper can do it, but I'm not sure. When I need to find usages, I do it the poor-man's way and remove the implicit operator, recompile and find the errors.
I suppose theoretically the compiler might then miss a case if it can use a different implicit operator (or switch to an "object" type overload of a method), but it tends to work for my usages. I'm sure there's a better solution, but it's worked for me so far.
EDIT: Just had a thought and tested it. Marking your implicit operator as [Obsolete]
will actually result in a compiler warning wherever you use it! I suppose this will catch those corner cases where there are other valid overloads that you'd miss having removed the implicit operator altogether.
来源:https://stackoverflow.com/questions/10585594/how-to-get-find-usages-working-with-implicit-operator-methods