我正在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
的泛型类型参数?
答案 0 :(得分:7)
它不漂亮,但这对我有用:
CodeInterface @interface;
// FullName = "IQuery<[FullNameOfType]>
string firstArgument = @interface.FullName.Split('<', '>')[1];