EnvDTE 并从属性中获取常量值

EnvDTE and getting constant value from attribute

我有一个 class 和常量字符串路由:

public class Routes
{
   public const string Route1 = "api/customers";
}

还有一个 WebApi 控制器 class 具有 Route 属性:

public class CustomerController : ApiController
{
   [Route(Routes.Route1)]
   public IList<Customer> GetCustomers()
   {..}
}

我需要使用 EnvDTE.

从属性中获取常量的字符串值

我能够接收 CodeAttribute2 对象,然后是 CodeAttributeArgument 的值,但它的值只是 "Routes.Route1"。

如何导航到 Route 类型然后导航到 Route1 常量?

简短的回答(假设您事先知道该类型驻留在您的项目的文件中,而不是在另一个引用的项目或编译的引用中)是使用 EnvDTE.Project.CodeModel 然后导航代码元素递归(参见 HOWTO: Navigate the code elements of a file from a Visual Studio .NET macro or add-in 中的方法),直到找到 FullName 为“.Route.Route1”的元素,它应该是 EnvDTE.CodeVariable,然后使用 CodeVariable.InitExpression 来获取 "api/customers" 值。

长答案是:

How do I get a System.Type from a type name?

How to get a System.Type from an EnvDTE.CodeTypeRef or EnvDTE.CodeClass