开发者

Tool for examining potential casting problems in C#

开发者 https://www.devze.com 2023-01-31 19:49 出处:网络
I have the following situation on my hands. In the project I work on we have this abstract class A which has two descendants, A_concrete1 and A_concrete2. These two were around for some time now.

I have the following situation on my hands. In the project I work on we have this abstract class A which has two descendants, A_concrete1 and A_concrete2. These two were around for some time now.

The time has come to add the third descendant, A_concrete3. The problem is, a lot of time in existing codebase you'll find something like that:

A instance;
// ...
// assignment of instance
// ...
if (!(A is A_concrete1))
  A_concrete2 = (A_concrete2)A;

So now, when A has more th开发者_运维百科an two descendants, this code is obviously broken and will fail at runtime.

My question is: how do I locate all these situations automatically so I could fix them? What is the best way/tool to do it? I tried to use Resharper, but it doesn't provide anything for casting analysis. So I'd be glad to hear some suggestions and pointers on this one.

Thanks in advance


The best way to do it is to have methods in A (that might be overridden in the subclasses) and for any code given an A to use it only to call methods of A, and to never cast it to either subclass. That way you won't have to do this again.

Probably Find in Files (the toolbar button features binoculars on a file folder) is the best way to find (A_concrete2) and is A_concrete1. But don't just get in there and replace the if with a bunch of ifs - change A so it's a more appropriate base class.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号