通用类型传递和使用,我可以执行以下操作吗?

Mat*_*olf 7 c# generics reflection interface

我试着弄清楚如何在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;
        }
    }
Run Code Online (Sandbox Code Playgroud)

Kie*_*one 9

定义一个接口DoThis,MyAction实现它,并将Ttype参数约束为它的实例where T : IMyInterface