Calling the constructor of a subclass from a static base class method

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

However, in C # this does not work. Heck!

So ... does anyone know how I can “update” a subclass from a static base class method?

Something like that...

public class MyBaseClass{

    string name;

    public static Object GimmeOne(string name){

     // What would I replace 'this' 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 that I can (and usually) just use the constructors directly, but we have a special need to call the common member in the base class, so I ask. Again, Objective-C let me do this. Hope C # too.

So ... any participants?

+3
2

# . , , :

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;
    }
}

new() , , , , . :

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

, . # . GimmeOne , MyBaseClass, SubClass1 - - "" MyBaseClass. Reflection , , MyBaseClass.

, , . factory . , , , , factory ( , , , ).

0

Source: https://habr.com/ru/post/1763934/


All Articles