【问题标题】:How to call static method of static generic class with C# Reflection?如何使用 C# 反射调用静态泛型类的静态方法?
【发布时间】:2018-10-30 17:26:28
【问题描述】:

我有许多具有这些实现的类:

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 方法?

最好的问候。

【问题讨论】:

标签: c# dynamic reflection generic-programming


【解决方案1】:

这样的事情应该可以工作:

// 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]);

【讨论】:

  • 这行代码没有编译:Type openGeneric = typeof(WindowsServiceConfiguration); WindowsServiceConfiguration 需要很多参数
  • 已修复。这是一个错字。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-09
  • 2011-07-14
  • 2012-08-08
相关资源
最近更新 更多