有没有办法获得一个类型和所有后续基类型的成员? [英] Is there any way to get Members of a type and all subsequent base types?

查看:46
本文介绍了有没有办法获得一个类型和所有后续基类型的成员?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个`ITypeSymbol' 对象.如果我调用 >,它给了我当前类型的成员,而不是基础.我知道我可以使用 BaseType 属性挖掘它,并有一些迭代代码来获取所有属性.

I have an `ITypeSymbol' object. If I call GetMembers, it gives me the members of the current type, not the base. I know I can dig it using BaseType property and have some iterative code to fetch all the properties.

是否有更简单的方法来获取所有成员,而不管继承层次结构的级别如何?

Is there any easier way to fetch all members regardless of level at the inheritance hierarchy?

推荐答案

如果您正在寻找所有成员,无论他们是否可以访问:

没有公共 API 可以做到这一点,而且 Roslyn 团队的内部方法与您所描述的或多或少相同.

There is no public API to do this, and internally the Roslyn team's approach is more or less the same as what you've described.

看看internal扩展方法GetBaseTypesAndThis().您可以将其复制到您自己的扩展方法中并按如下方式使用它:

Take a look at the internal extension method GetBaseTypesAndThis(). You could copy this out into your own extension method and use it as follows:

var tree = CSharpSyntaxTree.ParseText(@"
public class A
{
    public void AMember()
    {
    }
}

public class B : A
{
    public void BMember()
    {
    }
}

public class C: B  //<- We will be analyzing this type.
{
    public void CMember()
    {
    }
    //Do you want this to hide B.BMember or not?
    new public void BMember()
    {
    }
}");

var Mscorlib = MetadataReference.CreateFromAssembly(typeof(object).Assembly);
var compilation = CSharpCompilation.Create("MyCompilation",
    syntaxTrees: new[] { tree }, references: new[] { Mscorlib });
var model = compilation.GetSemanticModel(tree);

var classC = tree.GetRoot().DescendantNodes().OfType<ClassDeclarationSyntax>().Last();
var typeC = (ITypeSymbol)model.GetDeclaredSymbol(classC);
//Get all members. Note that accessibility isn't considered.
var members = typeC.GetBaseTypesAndThis().SelectMany(n => n.GetMembers());

以下是GetBaseTypesAndThis()

public static IEnumerable<ITypeSymbol> GetBaseTypesAndThis(this ITypeSymbol type)
{
    var current = type;
    while (current != null)
    {
        yield return current;
        current = current.BaseType;
    }
}

要检查可访问性,请在以下行中放置 where 条件以检查可访问性:

To check for accessibility put a where condition in the following line to check for accessibility:

typeC.GetBaseTypesAndThis().SelectMany(n => n.GetMembers().Where(x => x.DeclaredAccessibility == Accessibility.Public));`

这篇关于有没有办法获得一个类型和所有后续基类型的成员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆