ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

c#-从泛型类型确定类型派生

2019-10-23 18:08:57  阅读:313  来源: 互联网

标签:derived-class reflection generics c


我有以下实用程序例程,用于确定类型是否从特定类型派生:

private static bool DerivesFrom(Type rType, Type rDerivedType)
{
    while ((rType != null) && ((rType != rDerivedType)))
        rType = rType.BaseType;
    return (rType == rDerivedType);
}

(实际上,我不知道是否有更方便的方法来测试派生…)

问题是我想确定一个类型是否派生自一个泛型类型,但是没有指定泛型参数.

例如,我可以写:

DerivesFrom(typeof(ClassA), typeof(MyGenericClass<ClassB>))

但我需要以下

DerivesFrom(typeof(ClassA), typeof(MyGenericClass))

我该如何实现?

基于Darin Miritrov的示例,这是一个示例应用程序:

using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;

namespace ConsoleApplication1
{
    public class MyGenericClass<T> { }
    public class ClassB {}
    public class ClassA : MyGenericClass<ClassB> { }

    class Program
    {
        static void Main()
        {
            bool result = DerivesFrom(typeof(ClassA), typeof(MyGenericClass<>));
            Console.WriteLine(result); // prints **false**
        }

        private static bool DerivesFrom(Type rType, Type rDerivedType)
        {
            return rType.IsSubclassOf(rDerivedType);
        }
    }
}

解决方法:

您可以将通用参数保持打开状态:

DerivesFrom(typeof(ClassA), typeof(MyGenericClass<>));

应该管用.例:

public class ClassA { }
public class MyGenericClass<T>: ClassA { }

class Program
{
    static void Main()
    {
        var result = DerivesFrom(typeof(MyGenericClass<>), typeof(ClassA));
        Console.WriteLine(result); // prints True
    }

    private static bool DerivesFrom(Type rType, Type rDerivedType)
    {
        return rType.IsSubclassOf(rDerivedType);
    }
}

还要注意IsSubClassOf方法的用法,它应该简化DerivesFrom方法并破坏其目的.您也可以查看IsAssignableFrom方法.

标签:derived-class,reflection,generics,c
来源: https://codeday.me/bug/20191023/1914632.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有