c# - 如何使用泛型类型的类型参数作为方法参数的类型?
问题描述
有 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。
解决方案
您可以在 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> { }
推荐阅读
- python - Kivy 2.0.0 StringProperty 无法识别
- jquery - 仅发布 ASP.NET MVC 后更新 HTML.Partial
- html - 从字体真棒图标中删除底部填充
- c# - 您如何解析来自人机接口设备/HID 的信息?
- c# - 我想选择所有(用户)都在事件中注册的(事件)
- php - 使用 php 将包含网格布局的 html + css 转换为 .pdf
- python - Python:解包字节打包消息
- python - 格式化从数据框中绘制的表
- javascript - jQuery:单个变量中的多个选择器
- postgresql - 选择 Heroku Dataclip 上的所有表