首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

在C#中打开泛型类继承动态识别

在C#中,您可以使用反射来打开泛型类并继承动态识别。以下是一个示例代码:

代码语言:csharp
复制
using System;
using System.Reflection;

public class GenericBase<T>
{
    public virtual void DoSomething(T value)
    {
        Console.WriteLine("GenericBase: " + value);
    }
}

public class GenericDerived<T> : GenericBase<T>
{
    public override void DoSomething(T value)
    {
        Console.WriteLine("GenericDerived: " + value);
    }
}

public static class Program
{
    public static void Main(string[] args)
    {
        Type genericType = typeof(GenericDerived<>);
        Type[] typeArgs = { typeof(int) };
        Type specificType = genericType.MakeGenericType(typeArgs);

        object derivedInstance = Activator.CreateInstance(specificType);
        MethodInfo method = specificType.GetMethod("DoSomething");
        method.Invoke(derivedInstance, new object[] { 42 });
    }
}

在这个例子中,我们定义了一个泛型基类GenericBase<T>和一个泛型派生类GenericDerived<T>。我们使用反射来创建一个泛型派生类的实例,并动态识别其方法。

Main方法中,我们首先获取泛型派生类的类型,然后使用MakeGenericType方法创建一个具体的泛型类型。接下来,我们使用Activator.CreateInstance方法创建泛型派生类的实例。最后,我们使用GetMethod方法获取DoSomething方法,并使用Invoke方法调用它。

这个例子演示了如何在C#中使用反射来打开泛型类并继承动态识别。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

1分4秒

光学雨量计关于降雨测量误差

领券