简体   繁体   English

我该如何实例化此类?

[英]How can I instantiate this class?

Consider this declaration with generics: 考虑一下泛型的声明:

public class BaseNode<TNode> where TNode : BaseNode<TNode>
{
    public class Node : BaseNode<Node>
    {
        public Node() { }
    }
}

Is there a way to create an instance of class Node from outside the base class? 有没有一种方法可以从基类外部创建Node类的实例? I have used this pattern before, but always leaving the derived classes outside of the base class. 我以前使用过这种模式,但始终将派生类留在基类之外。

How do you write the following without a compiler error? 如何编写以下内容而没有编译器错误?

var obj = new BaseNode<Node>.Node(); 
// error CS0246: The type or namespace name 'Node' could not be found

Have I created an un-instantiable class? 我是否创建了一个无法实例化的课程? Can it be initialized via reflection? 可以通过反射初始化吗?

You can instantiate that monster. 您可以实例化该怪物。 All you have to do is create your own class that inherits from Node : 您要做的就是创建自己的继承自Node的类:

public class MyNode : BaseNode<MyNode>.Node
{
}

Then you can instantiate it like this: 然后,您可以像这样实例化它:

BaseNode<MyNode> obj = new BaseNode<MyNode>();

Why you would want to do this, though, is a different matter entirely... 但是,为什么要这样做,完全是另一回事...

Add a static factory method: 添加静态工厂方法:

public static Node Create<T>()
{
    return // your new Node
}

And call it thusly: 并这样称呼它:

var foo = BaseNode<Node>.Create<Node>();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM