【问题标题】:How to get the generic type parameters for a ENVDTE CodeInterface?如何获取 ENVDTE CodeInterface 的泛型类型参数?
【发布时间】:2012-09-21 15:59:48
【问题描述】:

我正在 Visual Studio 2010 中编写 T4 模板,并根据项目中的现有类生成代码。我需要生成的代码取决于类实现的接口的泛型类型参数,但我看不到通过 Visual Studio 核心自动化 EnvDTE 访问该信息的方法。这是我需要分析的一个类的示例:

public class GetCustomerByIdQuery : IQuery<Customer>
{
    public int CustomerId { get; set; }
}

根据这个定义,我想生成如下所示的代码(使用 T4):

[OperationContract]
public Customer ExecuteGetCustomerByIdQuery(GetCustomerByIdQuery query)
{
    return (Customer)QueryService.ExecuteQuery(query);
}

目前,我的 T4 模板中的代码看起来有点像这样:

CodeClass2 codeClass = GetCodeClass();

CodeInterface @interface = codeClass.ImplementedInterfaces
    .OfType<CodeInterface>()
    .FirstOrDefault();

// Here I want to do something like this, but this doesn't work:
// CodeClass2[] arguments = @interface.GetGenericTypeArguments();

但是如何获得CodeInterface 的泛型类型参数?

【问题讨论】:

  • 为什么不Type[] types = @interface.GenericTypeArguments()
  • @Cuong:我如何准确地获得接口的那个 Type 实例?不要忘记 Visual Studio 互操作适用于 CodeClass 实例,而不适用于 Type
  • 我遇到了同样的问题,但更糟糕的是,ImplementedInterfaces 的计数为 0。必须有更好的方法来获取类实现中的泛型...

标签: c# .net visual-studio t4 envdte


【解决方案1】:

它不漂亮,但这对我有用:

CodeInterface @interface;

// FullName = "IQuery<[FullNameOfType]>
string firstArgument = @interface.FullName.Split('<', '>')[1];

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-10
    • 1970-01-01
    • 2011-09-03
    相关资源
    最近更新 更多