检查方法是否实现了标有属性的接口方法
Check if method implements interface method marked with attribute
Roslyn 是否可以确定 class 方法是否实现了一些标有属性的接口方法?
特别是在 wcf 中,我们使用接口描述服务契约。它的每个方法都应该用 OperationContractAttribute
标记,就像下面的示例
[ServiceContract]
public interface ISimleService
{
[OperationContract]
string GetData(int value);
}
public class SimleService : ISimleService
{
public string GetData(int value)
{
return string.Format("You entered: {0}", value);
}
}
在 Roslyn ISymbol
接口中为我们提供了 GetAttributes() 方法,但在 SimleService.GetData()
方法上调用了它 returns 0。在 ISimleService.GetData()
声明上调用了它 returns OperationContractAttribute
符合预期。
所以一般来说,我必须检查 class 层次结构以找到所有实现的接口,然后遍历层次结构以找到合适的 methods.This 是一个困难的方法,我想应该有一个更简单的方法。
是的,可以查明方法是否是接口方法的实现。这是执行此操作的代码:
methodSymbol.ContainingType
.AllInterfaces
.SelectMany(@interface => @interface.GetMembers().OfType<IMethodSymbol>())
.Any(method => methodSymbol.Equals(methodSymbol.ContainingType.FindImplementationForInterfaceMember(method)));
你可以修改它来实际抓取实现的方法,然后你可以检查属性。
Roslyn 是否可以确定 class 方法是否实现了一些标有属性的接口方法?
特别是在 wcf 中,我们使用接口描述服务契约。它的每个方法都应该用 OperationContractAttribute
标记,就像下面的示例
[ServiceContract]
public interface ISimleService
{
[OperationContract]
string GetData(int value);
}
public class SimleService : ISimleService
{
public string GetData(int value)
{
return string.Format("You entered: {0}", value);
}
}
在 Roslyn ISymbol
接口中为我们提供了 GetAttributes() 方法,但在 SimleService.GetData()
方法上调用了它 returns 0。在 ISimleService.GetData()
声明上调用了它 returns OperationContractAttribute
符合预期。
所以一般来说,我必须检查 class 层次结构以找到所有实现的接口,然后遍历层次结构以找到合适的 methods.This 是一个困难的方法,我想应该有一个更简单的方法。
是的,可以查明方法是否是接口方法的实现。这是执行此操作的代码:
methodSymbol.ContainingType
.AllInterfaces
.SelectMany(@interface => @interface.GetMembers().OfType<IMethodSymbol>())
.Any(method => methodSymbol.Equals(methodSymbol.ContainingType.FindImplementationForInterfaceMember(method)));
你可以修改它来实际抓取实现的方法,然后你可以检查属性。