如何用C#Reflection调用静态泛型类的静态方法?

时间:2018-05-21 05:15:27

标签: c# dynamic reflection generic-programming

我有很多这些实现的类:

internal static class WindowsServiceConfiguration<T, Y> where T : WindowsServiceJobContainer<Y>, new() where Y : IJob, new()
{
    internal static void Create()
    {            
    }
}

public class WindowsServiceJobContainer<T> : IWindowsService where T : IJob, new()
{
    private T Job { get; } = new T();
    private IJobExecutionContext ExecutionContext { get; }

    public void Start()
    {

    }

    public void Install()
    {

    }

    public void Pause()
    {

    }

    public void Resume()
    {

    }

    public void Stop()
    {

    }

    public void UnInstall()
    {

    }
}

public interface IWindowsService
{
    void Start();
    void Stop();
    void Install();
    void UnInstall();
    void Pause();
    void Resume();
}

public class SyncMarketCommisionsJob : IJob
{                
    public void Execute(IJobExecutionContext context)
    {            
    }
}

public interface IJob
{     
    void Execute(IJobExecutionContext context);
}

我想通过反射调用WindowsServiceConfiguration静态类的Create()方法,如下所示:

WindowsServiceConfiguration<WindowsServiceJobContainer<SyncMarketCommisionsJob>, SyncMarketCommisionsJob>.Create();

我不知道如何通过使用Activator或类似的东西来调用我的C#代码中的Create方法?

最好的问候。

1 个答案:

答案 0 :(得分:0)

这样的事情应该有效:

// Get the type info for the open type
Type openGeneric = typeof(WindowsServiceConfiguration<,>);
// Make a type for a specific value of T
Type closedGeneric = openGeneric.MakeGenericType(typeof(WindowsServiceJobContainer<SyncMarketCommisionsJob>), typeof(SyncMarketCommisionsJob));
// Find the desired method
MethodInfo method = closedGeneric.GetMethod("Create", BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.InvokeMethod);
// Invoke the static method
method.Invoke(null, new object[0]);