You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

通过反射调用泛型静态类的Create方法

首先先把你给出的类结构贴出来方便参考:

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<WindowsServiceJobContainer<SyncMarketCommisionsJob>, SyncMarketCommisionsJob>.Create(),而不是硬编码泛型参数对吧?下面是具体的实现步骤:

核心思路

反射调用泛型静态方法的关键是先构造出闭合的泛型类型,再从中获取目标方法并调用。

完整实现代码

// 1. 先拿到你的Job类型
Type jobType = typeof(SyncMarketCommisionsJob);

// 2. 构造WindowsServiceJobContainer<SyncMarketCommisionsJob>这个泛型类型
Type containerGenericType = typeof(WindowsServiceJobContainer<>);
Type closedContainerType = containerGenericType.MakeGenericType(jobType);

// 3. 构造WindowsServiceConfiguration<T,Y>的闭合泛型类型
Type configGenericType = typeof(WindowsServiceConfiguration<,>);
Type closedConfigType = configGenericType.MakeGenericType(closedContainerType, jobType);

// 4. 获取internal的Create静态方法(注意必须指定BindingFlags,否则找不到非公开方法)
MethodInfo createMethod = closedConfigType.GetMethod(
    "Create",
    BindingFlags.Static | BindingFlags.NonPublic,
    Type.DefaultBinder,
    Type.EmptyTypes, // 无参数
    null
);

// 5. 调用方法:静态方法Invoke的第一个参数传null
createMethod?.Invoke(null, null);

关键细节说明

  • 访问权限问题:因为Create是internal方法,所以获取方法时必须加上BindingFlags.NonPublic,同时配合BindingFlags.Static才能定位到这个方法。
  • 泛型类型构造:对于有多个泛型参数的类型,比如WindowsServiceConfiguration<,>,要用逗号占位表示参数数量(2个参数就写<,>),然后通过MakeGenericType传入具体的类型参数生成闭合类型。
  • 动态扩展:如果以后要换其他IJob实现,只需要把jobType换成对应的类型(比如typeof(AnotherJob)),剩下的逻辑可以直接复用。

内容的提问来源于stack exchange,提问作者Mohammad Gorji

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 07:18:52