将泛型类传递给非泛型方法 [英] Passing a generic class to a non generic method
问题描述
假设我们有以下通用类:
Say we have a the following generic class:
public class Node<T> {}
但是我们需要将其传递给非通用类中的非通用方法:
But we need to pass this to a non generic method in a none generic class :
public class classname
{
public void SomeMethod(Node?? node) { }
}
How can this be done?
推荐答案
泛型类可以从非泛型类继承.
The generic class could inherit from a non-generic class.
public class NodeBase
{
// Base class stuff here
public virtual void NodeMethod()
{
// Do something
}
}
public class Note<t> : NodeBase
{
// Generic class stuff here
public override void NodeMethod()
{
// Do something special
}
}
然后您可以通过以下方式将其移交给该方法:
Then you can hand it over to the method this way:
public class classname
{
public void SomeMethod( NodeBase node)
{
// Use methods declared in base class
node.NodeMethod();
}
}
Mehdi,
回答这个问题是一件微不足道的事情.您可以自己回答,只需要合乎逻辑.
您需要从非泛型方法开始,因为这是最大的限制(顺便说一句,为什么它不是泛型的?好,我知道为什么会这样).我们有哪些变体?
首先,它可以期望任何固定的参数类型;在这种情况下,它将确定通用参数:
Mehdi,
Answering this question is quite a trivial thing. You could answer by yourself, you just need to be logical.
You need to start with non-generic method, as this is the most limiting (by the way, why it is not generic? OK, I understand why it could be). What variants do we have?
First, it could expect any fixed parameter type; in this case, it will determine the generic parameter:
public class Node<T> {/*...*/}
public class classname
{
public void SomeMethod(Parameter node) {/*...*/}
}
public class Parameter {/*...*/}
//...
Node<Parameter> parameter = ...
classname instance = ...
instance.SomeMethod(parameter); //isn't it?
另一个变体是使用更宽的类型.让我们从最宽处开始,它是System.Object
:
Another variant is using wider type. Let starts with the widest, which is System.Object
:
public class Node<T> {/*...*/}
public class classname
{
public void SomeMethod(System.Object node) {/*...*/}
}
public class Parameter {/*...*/} //this is any type again, always is System.Object
//...
Node<Parameter> parameter = ...
classname instance = ...
instance.SomeMethod(parameter); //same thing
最后,与上述相同,但有通用约束;这个想法是使用最广泛的通用类型而不是System.Object
:
And finally, the same case as above but with generic constraint; the idea is to use the widest common type instead of System.Object
:
public abstract class AbstractParameter {/*...*/}
public class Node<T> where T: AbstractParameter {/*...*/}
public class classname
{
public void SomeMethod(AbstractParameter node) {/*...*/}
}
public class Parameter : AbstractParameter {/*...*/} //this time, any type but derived from AbstractParameter
//...
Node<Parameter> parameter = ...
classname instance = ...
instance.SomeMethod(parameter); //isn't it?
此外,还有一个带有接口的变量而不是抽象类,基本上是相同的.
仅此而已.
Also, there is a variant with interface instead of abstract class, essentially the same.
That''s all, it looks like.
这篇关于将泛型类传递给非泛型方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!