【问题标题】:Roslyn - Interface member not found using FindImplementationForInterfaceMemberRoslyn - 使用 FindImplementationForInterfaceMember 找不到接口成员
【发布时间】:2017-11-28 23:57:59
【问题描述】:

有人能解释一下为什么使用'FindImplementationForInterfaceMember()'方法找不到类A中M1的接口实现吗?

所有变量都引用了一个符号,除了 'am1' 为空。

            string source = @"
namespace Lib
{
    public interface IA<T>
    {
        void M1();
    }

    public class A<T> : IA<T>
    {
        public void M1() { }
    }
}
";
        var compilation = CSharpCompilation.Create("MyCompilation")
            .AddSyntaxTrees(CSharpSyntaxTree.ParseText(source));

        var global = compilation.GlobalNamespace;
        var lib = global.GetMembers("Lib").OfType<INamespaceSymbol>().Single();
        var ia = lib.GetTypeMembers("IA").OfType<ITypeSymbol>().Single();
        var a = lib.GetTypeMembers("A").OfType<ITypeSymbol>().Single();

        var iam1 = ia.GetMembers("M1").OfType<IMethodSymbol>().Single();
        var am1 = a.FindImplementationForInterfaceMember(iam1);

【问题讨论】:

    标签: c# roslyn roslyn-code-analysis


    【解决方案1】:

    ia(因此它的成员am1)是一个开放(或未构造的)泛型类型,没有指定类型参数。

    类(及其方法)实现封闭(构造)泛型类型,它们为类型参数指定特定类型。

    因此,FindImplementationForInterfaceMember() 只能在您将方法传递给封闭接口时才能返回任何内容。

    在您的特定情况下,您需要通过指定类的类型参数来构造一个封闭的接口(因为该类使用自己的T 实现IA&lt;T&gt;)。如果你的类以不同的方式实现(例如,: IA&lt;List&lt;T&gt;&gt;),它会更加复杂。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多