好的,我从文档(来自here和here)知道如何使用泛型方法编写简单的泛型类。但在我的情况下,我有不同的东西,我不知道什么是实现这一点的正确方法。所以这就是我在半伪代码中所拥有的
// This is a base class
public class Parent_Class<T>{
T field_1;
public void method_1<T2>(){
T2 local_variable = new T2();
}
}
// ^^^ Is it right?? And is it possible to inherit from this class in this way (option 1):
public Child_Class : Parent_Class <Class_1>{
public void method_1(){
base.method_1<Class_2>();
// ^^^ will this work???
}
}
我看到另一个替代方案可能会看到半伪代码:
// This is a base class
public class Parent_Class<T, T2>{
T field_1;
public void method_1<T2>(){
T2 local_variable = new T2();
}
// ^^^ should it be declared like public void method_1<T2>
// or can we simply declare it with public void method_1(){
}
// ^^^ Is it right?? And is it possible to inherit from this class in this way (option 1):
public Child_Class : Parent_Class <Class_1, Class_2>{
public void method_1(){
base.method_1<Class_2>();
// ^^^ should I call it like this? or can I do simply
//base.method_1();
}
}
因此,正如您所看到的,有一些泛型类型。我把我的问题放在代码中,希望有人能指出我正确的方向。谢谢!
答案 0 :(得分:1)
由于问题已经减少为将args传递给template type
构造函数..
using System;
class A
{
public A() { }
}
class B
{
private int data;
public B() { }
public B(int x) { data = x; }
public int Data { get { return data; } }
}
class Base<T1, T2> where T2 : new()
{
private T1 a;
public void Method(object[] args)
{
//pass args to T2 constructor
T2 b = (T2)Activator.CreateInstance(typeof(T2), args);
}
}
class Derived : Base<A,B>
{
public new void Method(object[] args)
{
base.Method(args);
}
}
class Test
{
static void Main()
{
Derived d = new Derived();
d.Method(new object[]{ 1 });
}
}