从静态基类方法调用子类构造函数 [英] Calling subclass constructor from static base class method
问题描述
好吧……在目标C中,您可以使用 new this()从基类的静态方法中创建一个子类,因为在静态方法中, this是指该类,而不是实例。当我第一次发现它并且经常使用它时,这真是一个非常酷的发现。
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.
但是,在C#中不起作用。
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?
类似这样的事情……
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");
是的,我知道我可以(并且通常会)直接使用构造函数,但是我们有在基类上调用共享成员的特定需求,这就是我要问的原因。同样,目标C让我执行此操作。希望C#也是。
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#没有与此完全相同的东西。但是,您可以通过使用如下通用类型约束来解决此问题:
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;
}
}
new()约束表示存在无参数构造函数-您没有这么做,但我们将其隐藏起来以向消费者隐藏。然后可以像这样调用它:
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");
这篇关于从静态基类方法调用子类构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!