.net core 泛型

 

using System;
using System.Linq;
using System.Reflection;
 
public interface IGenericInterface<T>
{
    void DoSomething();
}
 
public class GenericInterfaceImpl<T> : IGenericInterface<T>
{
    public void DoSomething()
    {
        Console.WriteLine($"Doing something with {typeof(T).Name}");
    }
}
 
public class Program
{
    public static void Main(string[] args)
    {
        var interfaceType = typeof(IGenericInterface<>); // 泛型接口的定义
        var implementationType = Assembly.GetExecutingAssembly()
                                         .GetTypes()
                                         .FirstOrDefault(t => t.IsGenericType && 
                                                               t.GetInterfaces().Any(i => i.IsGenericType && 
                                                                                         i.GetGenericTypeDefinition() == interfaceType));
 
        if (implementationType != null)
        {
            var specificType = implementationType.MakeGenericType(typeof(int)); // 替换为你需要的类型参数
            var instance = Activator.CreateInstance(specificType);
            var method = specificType.GetMethod("DoSomething");
            method.Invoke(instance, null);
        }
    }
}

  

posted on 2024-07-28 18:36  是水饺不是水饺  阅读(5)  评论(0)    收藏  举报

导航