是否可以在继承的静态方法中检测类上下文? [英] Is it possible to detect class context in an inherited static method?

查看:49
本文介绍了是否可以在继承的静态方法中检测类上下文?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,这个标题有点不清楚,但是除了解释它之外,我想不出更好的方法来放置它...

OK, that title is a little unclear, but I can't think of a better way of putting it, other than explaining it...

说我有一个 Animal 类,带有静态的通用方法:

Say I have a class Animal, with a static, generic method:

public static T Create<T>() where T : Animal {
  // stuff to create, initialize and return an animal of type T
}

我有 Dog Cat Hamster 等子类.为了获得 Dog ,我可以写:

And I have subclasses Dog, Cat, Hamster etc. In order to get a Dog, I can write:

Dog d = Animal.Create<Dog>();

Dog d = Dog.Create<Dog>();

这实际上是同一回事.但是不得不多次编写 Dog 似乎有点愚蠢,因为我已经通过 Dog 子类调用了静态方法.

which is really the same thing. But it seems kinda silly to have to write Dog so many times, since I'm already invoking the static method through the Dog subclass.

您能想到在基类中编写 Create()方法的任何巧妙方法,以便我可以调用

Can you think of any clever way of writing a Create() method in the base class so that I could invoke

Dog d = Dog.Create();
Cat c = Cat.Create();
Hamster h = Hamster.Create();

是否没有在每个子类中编写 Create()方法?

without writing a Create() method in each of the subclasses?

推荐答案

您可以使Animal类具有通用性.

You can make the Animal class generic.

class Animal<T> where T : Animal<T>
{
    public static T Create()
    {
        // Don't know what you'll be able to do here
    }
}

class Dog : Animal<Dog>
{

}

但是 Animal 类如何知道如何创建派生类型的实例?

But how the Animal class knows how to create instances of derived types?

这篇关于是否可以在继承的静态方法中检测类上下文?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆