开发者

Calling subclass constructor from static base class method

Ok... in Objective C you can new up a subclass from a static method in the base class with 'new this()' because in a static method, 'this' refers to the class, not the instance. That was a pretty damn cool find when I first found it and I've used it often.

However, in C# that doesn't work. Damn!

So... anyone know how I can 'new' up a subclass from within a static base class method?

Something like this...

public class MyBaseClass{

    string name;

    public static Object GimmeOne(string name){

     // What would I replace 'this' 开发者_StackOverflow社区with in C#?
        return new this(name); 

    }

    public MyBaseClass(string name){
        this.name = name;
    }

}

// No need to write redundant constructors
   public class SubClass1 : MyBaseClass{ }
   public class SubClass2 : MyBaseClass{ }
   public class SubClass3 : MyBaseClass{ }

SubClass1 foo = SubClass1.GimmeOne("I am Foo");

And yes, I know I can (and normally would) just use the constructors directly, but we have a specific need to call a shared member on the base class so that's why I'm asking. Again, Objective C let's me do this. Hoping C# does too.

So... any takers?


C# doesn't have any exact equivalent to that. However, you could potentially get around this by using generic type constraints like this:

public class MyBaseClass
{
    public string Name { get; private set; }

    public static T GimmeOne<T>(string name) where T : MyBaseClass, new()
    {
        return new T() { Name = name };
    }

    protected MyBaseClass()
    {
    }

    protected MyBaseClass(string name)
    {
        this.Name = name;
    }
}

The new() constraint says there is a parameterless constructor - which your didn't but we make it private to hide that from consumers. Then it could be invoked like this:

var foo = SubClass1.GimmeOne<SubClass1>("I am Foo");


Sorry, you can't do this. C# is morally opposed to static method inheritance. That GimmeOne method will never have any type other than MyBaseClass, and calling it from SubClass1 doesn't matter- it's still "really" a MyBaseClass call. The Reflection libraries could do this construction, but you'd never get anything other than a MyBaseClass out of it.

If you're calling a static method, presumably you know which subclass you're calling it from. Create a different factory method for each subclass. If you're actually trying to do this by instance, you should probably use a non-static virtual factory method (which will automatically call the most derived form of the function, which is probably what you want) instead.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜