I have the following basic object factory for when I want some members of a class hierarchy to have special construction code and any other members to have generic constructors.
My problem here is that TileFactory doesn't have the method GetInstance--my program won't compile if I try to call TileFactory.GetInstance(). Any advice?
public static class ObjectFactory&l开发者_运维问答t;K>
{
public static T GetInstance<T>() where T : K
{
T obj = (T)Activator.CreateInstance(typeof(T));
return obj;
}
//snip
}
}
//snip
public static class TileFactory : ObjectFactory<Tile>
{
}
Why can't I inherit static classes?
Citation from here:
This is actually by design. There seems to be no good reason to inherit a static class. It has public static members that you can always access via the class name itself. The only reasons I have seen for inheriting static stuff have been bad ones, such as saving a couple of characters of typing.
There may be reason to consider mechanisms to bring static members directly into scope (and we will in fact consider this after the Orcas product cycle), but static class inheritance is not the way to go: It is the wrong mechanism to use, and works only for static members that happen to reside in a static class.
(Mads Torgersen, C# Language PM)
Other opinions from channel9
Inheritance in .NET works only on instance base. Static methods are defined on the type level not on the instance level. That is why overriding doesn't work with static methods/properties/events...
Static methods are only held once in memory. There is no virtual table etc. that is created for them.
If you invoke an instance method in .NET, you always give it the current instance. This is hidden by the .NET runtime, but it happens. Each instance method has as first argument a pointer (reference) to the object that the method is run on. This doesn't happen with static methods (as they are defined on type level). How should the compiler decide to select the method to invoke?
(littleguru)
And as a valuable idea, littleguru has a partial "workaround" for this issue: the Singleton pattern.
http://www.dofactory.com/Patterns/PatternSingleton.aspx
There is no inheritance for static things. A workaround is to use singletons.
精彩评论