如何获取ENVDTE CodeInterface的泛型类型参数?

9

我正在使用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()呢? - cuongle
@Cuong:我该如何准确获取接口的Type实例?别忘了,Visual Studio互操作使用的是CodeClass实例,而不是Type。 - Steven
1
我遇到了同样的问题,但更糟糕的是ImplementedInterfaces计数为0。必须有更好的方法来获取类实现中的泛型... - James Hancock
1个回答

7

虽然不太美观,但这对我来说很有效:

CodeInterface @interface;

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接