本文介绍了获取罗斯林完全合格的元数据名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要得到一个特定的符号的全名CLR。这意味着,对于泛型类型,我需要的`1 `2 等附加类型。现在, ISymbol 已经有一个属性 MetadataName 这正是这么做的。但它排除了周围的类型和命名空间,只给手头的符号的名称。

I need to get the full CLR name of a particular symbol. This means that for generic types I need the `1, `2, etc. appended to types. Now, ISymbol already has a property MetadataName which does exactly that. But it excludes surrounding types and namespaces, only giving the name of the symbol at hand.

获取一个完全合格的名称,即通过<$ C $常见的选项C> ToDisplayString 在这里所做的不是那么回事,因为它不会使用 MetadataName 为它的各个部分。

The usual option for getting a fully-qualified name, i.e. via ToDisplayString doesn't quite work here because it will not use the MetadataName for its various parts.

有没有这样的内置的东西吗?还是我刚才串联 ContainingSymbol 链s的之间? (?以及是否有指向哪里这个假设打破了)

Is there anything like this built-in? Or do I have to just concatenate the chain of ContainingSymbols with . in between? (And are there points where this assumption breaks down?)

编辑:只注意到你需要一个 + 个别名之间,如果是包含在其他类型的类型,但除此之外,使用应该工作,我猜。

Just noticed that you need a + in between individual names if it's a type contained in another type, but apart from that, using . should work, I guess.

推荐答案

目前,有没有更好的解决办法,我使用以下内容:

For now, having no better solution, I'm using the following:

public static string GetFullMetadataName(this INamespaceOrTypeSymbol symbol) {
  ISymbol s = symbol;
  var sb = new StringBuilder(s.MetadataName);

  var last = s;
  s = s.ContainingSymbol;
  while (!IsRootNamespace(s)) {
    if (s is ITypeSymbol && last is ITypeSymbol) {
      sb.Insert(0, '+');
    } else {
      sb.Insert(0, '.');
    }
    sb.Insert(0, s.MetadataName);
    s = s.ContainingSymbol;
  }

  return sb.ToString();
}

private static bool IsRootNamespace(ISymbol s) {
  return s is INamespaceSymbol && ((INamespaceSymbol)s).IsGlobalNamespace;
}



这似乎是现在的工作。罗斯林似乎对 SymbolDisplayFormat 内部标记,使之类的事情(最显着的,但不能访问到外面。

which seems to work for now. Roslyn seems to have internal flags for SymbolDisplayFormat that enable that sort of thing (most notably SymbolDisplayCompilerInternalOptions.UseArityForGenericTypes, but not accessible to the outside.

以上代码很可能是最近的.NET版本快使用追加而不是插入的StringBuilder ,但是这东西离开剖析。

Above code could probably be faster on recent .NET versions by using Append instead of Insert on the StringBuilder, but that's something to leave for profiling.

这篇关于获取罗斯林完全合格的元数据名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-17 01:29