【发布时间】:2012-12-09 00:55:15
【问题描述】:
我试图弄清楚如何访问 CallMe<T>() 类 DoSomething 中的静态方法。反射是这里唯一的解决方案吗?我不想实例化MyAction 类型的对象。此外,如果通过反射进行,是否有一种方法可以通过方法CallMe<T>() 中的反射创建该方法一次,然后多次调用它以对同一个“反射”方法执行多个操作?或者有什么比通过反射更好的方法吗?我基本上想创建模板实现样式类,例如 MyAction 来定义 byte[] DoThis(string text) 如何执行其职责。然后AskForSomething() 将指定正在使用的模板,并据此CallMe<T>() 将开始其工作。
public class AskSomething
{
public void AskForSomething()
{
DoSomething doSomething = new DoSomething();
doSomething.CallMe<MyAction>();
}
}
public class DoSomething
{
public void CallMe<T>()
{
Type type = typeof(T);
//Question: How can I access 'DoThis(string text)' here?
//Most likely by reflection?
}
}
public class MyAction
{
public static byte[] DoThis(string text)
{
byte[] ret = new byte[0]; //mock just to denote something is done and out comes a byte array
return ret;
}
}
【问题讨论】:
标签: c# generics reflection interface