开发者

use a specific overload without a cast?

I'd like to create some helper methods that are inheritance aware. I'd like them to work like virtual + override methods, yet without having to define a class hierarchy.

Here's how it might work with a cast. I'd like to be able to do this without the performance his of having multiple casts... and with开发者_C百科out defining yet another hierarchy:

class Program {
    static void Main(string[] args){
        var a = new A();
        var b = new B();

        var h = new Helper();
        h.DoSomething(a);
        h.DoSomething(b);
    }
}

public class A{}

public class B : A{}

public class Helper{
    public void DoSomething(A o){}

    public void DoSomething(B o){
        DoSomething((A)o);
    }
}

Any thoughts. Thanks in advance.


There's no performance penalty in having a cast from B to A - it's guaranteed to be correct, so there's no actual check to be performed. It's just delegating the method call.

Having said that, I'd actually recommend against using overloads with type hierarchies like this. Overloading can get pretty complicated...

(And as ever, don't assume a performance penalty without testing. Create a clean design, and test the performance. Only start bending things out of shape when you've found a problem.)


If B inherits from A then callers can simply provide an instance of B directly to:

public void DoSomething(A o){}
DoSomething(new B());

So there is no need for the other method. And to remove the ambiguity, the cast might be required, otherwise the compiler cannot determine what method you wish to call - as both are valid for the provided arguments.

Casts and performance should only be a concern if you can prove that the casting is causing problems. Trying to pre-empt things like this might just end up being premature optimisation.

That said, I have witnessed slow code paths of things that comprise of deep hierarchies (lots of overridden methods).


Why do you cast? As far as B : A you can pass your B into method accepting A:

public void DoSomething(A o) { }

DoSomething(new A());
DoSomething(new B());


You can declare both variables as of dynamic type (new .NET 4.0 Framework type - dynamic) or simply cast to dynamic. Take a look how dynamic allows resolve type in runtime and choose an appropriate overload method:

dynamic a = new A();
dynamic b = new B();
var h = new Helper();         

h.DoSomething(a); // will be called DoSomething(A o)        
h.DoSomething(b); // will be called DoSomething(B o)
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜