简体   繁体   English

检查基础 class 是否使用 Roslyn 实现了某个接口

[英]Checking whether the base class implements a certain interface using Roslyn

UPDATE:更新:

As it turns out, I am an idiot.事实证明,我是个白痴。 Instead of deriving from BaseClass , I made a typo and derived from another class with a very similar name -- let's say BassClass .我没有从BaseClass派生,而是打错字并从另一个名称非常相似的 class 派生 - 比如说BassClass

Many thanks to @canton7 for patiently guiding me through the debugging process.非常感谢 @canton7 耐心地指导我完成调试过程。


Here is some sample code:这是一些示例代码:

using System;

public interface SomeInterface {}

public class SomeAttribute : Attribute
{
}

[SomeAttribute]
public class BaseClass : SomeInterface
{
}

[SomeAttribute]
public class DerivedClass : BaseClass
{
}

Through inspecting the syntax node that represents DerivedClass , I want to be able to know that DerivedClass implements SomeInterface , by virtue of its being derived from BaseClass .通过检查表示DerivedClass的语法节点,我希望能够知道DerivedClass实现SomeInterface ,因为它是从BaseClass派生的。

Here is what I have so far:这是我到目前为止所拥有的:

SemanticModel semanticModel = context.Compilation.GetSemanticModel(candidateSyntax.SyntaxTree);
ISymbol candidateSymbol = semanticModel.GetDeclaredSymbol(candidateSyntax);

if (!ImplementsSomeInterface(candidateSymbol))
{
    // Do something
}

bool ImplementsSomeInterface(ISymbol symbol)
{
    return symbol is ITypeSymbol typeSymbol && typeSymbol.AllInterfaces.Any(i => i.Name == "SomeInterface");
}

ImplementsSomeInterface returns true for BaseClass but false for DerivedClass .对于BaseClassImplementsSomeInterface返回 true,而对于DerivedClass返回 false。 typeSymbol.AllInterfaces.Count() is 1 for BaseClass and 0 for DerivedClass . typeSymbol.AllInterfaces.Count()对于BaseClass为 1,对于DerivedClass为 0。

How should I implement the ImplementsSomeInterface method, so that it returns true also for DerivedClass ?我应该如何实现ImplementsSomeInterface方法,以便它也为DerivedClass返回 true ?

You can achieve it easily, using reflections:您可以使用反射轻松实现它:

var temp = typeof (B).GetInterfaces ().Contains (typeof (Isome));

If that's not the case, perhaps try write all of them to console, to check does it fetches those interfaces right.如果不是这种情况,也许尝试将它们全部写入控制台,以检查它是否正确获取了这些接口。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM