C#中具有多个参数的泛型类

本文关键字:参数 泛型类 | 更新日期: 2023-09-27 18:21:00

好的,我从文档中(从这里到这里)知道如何用泛型方法编写简单的泛型类。但在我的情况下,我有一些不同的东西,我不确定什么是实现这一点的正确方法。这就是我在半伪码中得到的

// 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();
    }
}

因此,正如您所看到的,存在泛型类型的混合。我把我的问题放在代码中,希望有人能给我指明正确的方向。谢谢

C#中具有多个参数的泛型类

由于问题已简化为将参数传递给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 });
    }
}