2012-09-30 49 views
9

我正在Visual Studio 2010中編寫一個T4模板,並基於項目中現有的類生成代碼。我需要生成的代碼取決於類實現的接口的泛型類型參數,但我沒有看到通過Visual Studio核心自動化EnvDTE訪問該信息的方法。這是一類的,我需要分析一個例子:如何獲取ENVDTE CodeInterface的泛型類型參數?

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

爲什麼不'類型[]類型= @ interface.GenericTypeArguments()'? –

+0

@Cuong:我該如何獲得該接口的Type實例?不要忘記,Visual Studio互操作與'CodeClass'實例一起工作,而不是'Type'。 – Steven

+1

我遇到了同樣的問題,但更糟糕的是,ImplementedInterfaces的計數爲0.必須有更好的方法來獲得類實現的泛型... –

回答

6

這不是很漂亮,但這樣做的伎倆對我來說:

CodeInterface @interface; 

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