首页 > 解决方案 > 如何使用泛型类型的类型参数作为方法参数的类型?

问题描述

有 1 个基类和 2 个子类:

class A<T> { }
class B : A<int> { }
class C : A<string> { }

我想使用这样的方法test

void test<T>(? param)
{
    // Do something, need to use param, no returns
}
void main()
{
    test<B>(1);        // ok!
    test<B>("1");      // Error!

    test<C>("1");      // ok!
    test<C>(1);        // Error!
}

我只想编写一个泛型类型T(在这种情况下:B 或 C),然后我得到泛型类型参数来限制param(在这种情况下:int 或 string)。

关键是要param根据T

如何编写方法test

PS:一个更具体的例子:

namespace T
{
    abstract class A<T>
    {
        public abstract void OnCreate(T param);
    }
    class B : A<int>
    {
        public override void OnCreate(int score)
        {
            int r = score + 1;
            Console.WriteLine(r);
        }
    }
    class C : A<string>
    {
        public override void OnCreate(string msg)
        {
            string r = $"msg:{msg}";
            Console.WriteLine(r);
        }
    }

    class Program
    {

        static void Main()
        {
            // already initialized elsewhere
            var b = new B();
            var c = new C();

            // Solution 1:
            b.OnCreate(1);
            c.OnCreate("this is a msg");

            // Solution 2:
            // I want to use method "run" to achieve solution 1, but I don't know how to write "run"
            run<B>(b, 1);
            run<C>(c, "this is a msg");
            // I want to limit param, if I write wrong type, then Error:
            run<B>(c, 1);       // Error!
            run<B>(b, "1");     // Error!    
            run<C>(c, 222);     // Error!
        }

        static void run<T>(T ins, ?? param) where ??
        {
            // Do Something
            Console.WriteLine("Use method run start");

            ins.OnCreate(param);

            // Do Something
            Console.WriteLine("Use method run end");
        }
    }
}

在此示例中,我想使用 Solution-2 而不是 Solution-1。

标签: c#generics

解决方案


您可以在 A 类中编写方法:

public static void Main()
{
    new B().test(1);
    new C().test("1");
}


abstract class A<T> {
   public void test(T value){
       Console.WriteLine(value);
   }
}
class B : A<int> {  }
class C : A<string> { }

推荐阅读