In C#, is it ok to virtualize every method?
This may make a lot of C# programmers cringe, but is it ok to virtual
-ize every method in a base class -- even if certain methods are never overridden?
The reason I need to do this is that I have a special case where I need to get C# to act like Java. It's actually an automatic program transformation of a Java program.
I'm thinking to mark any开发者_开发技巧 Java method that has no base method as virtual
, and any that do have an associated base method as override
.
Aside from a lack of flexibility, are there any other issues with doing it this way?
Yes it is okay, but not necessarily a good practice. Virtualization helps with two things: inheritance and decoupling (for things like unit testing or replacing out other classes with new ones). Prefer composition over inheritance in your OO design and you can use interfaces instead of virtuals with your classes. That will give you what you need for both unit testing and composition. But, with the speed of today's CPUs, I'd not worry terribly about the extra V-table lookup if everything is virtual.
So I suggest, if you can solve your problem by providing an interface for the java program, do that. Otherwise, don't lose any sleep over having the methods virtual.
Not only is this OK, but some applications need this.
nHibernate requires you to mark properties as virtual for mapping, for example.
This is ok. There will be no unwanted behaviors caused by this, and as far as I know, virtual methods do not cause the classes to slow down. So, why not?
精彩评论