【问题标题】:How to create CodeFunction2 with IEnumerable<> Type?如何使用 IEnumerable<> 类型创建 CodeFunction2?
【发布时间】:2009-10-12 15:38:51
【问题描述】:

我确实需要创建类似以下的内容,我正在构建 2 个类,第一个是名称为 tableNameAsSingular (即 AddressEntity) 的类,在我的第二个工作类中,我需要具有以下内容

public IEnumerable<AddressEntity> GetAddressEntity()
{
 // the good stuff...
}

创建函数时,我有以下内容..

Type t = Type.GetType("IEnumerable<" + tableNameAsSingular + ">");
CodeFunction2 finderFunction = (CodeFunction2)entityServiceClass.AddFunction("Get" + table.Name, vsCMFunction.vsCMFunctionFunction, t, -1, vsCMAccess.vsCMAccessPublic, null);

但 t 始终为空

当我执行Type.GetType(tableNameAsSingular) 时,它也会返回 null

我们将不胜感激任何帮助或指点。此外,如果有人知道大量的 EnvDTE 代码生成知识在哪里,我会非常感激!


更新

我现在已经尝试使用以下字符串作为字符串:

   public void AddFinderMethod()
    {
        string t = "IEnumerable<" + tableNameAsSingular + ">";
        CodeFunction2 finderFunction = (CodeFunction2)entityServiceClass.AddFunction("Get" + table.Name, vsCMFunction.vsCMFunctionFunction, t, -1, vsCMAccess.vsCMAccessPublic, null);
        // Code here remove as it does not get this far yet.
    }

但我在 AddFunction 方法中收到“IEnumerable&lt;ProductEntity&gt; is not a valid identifier”错误消息

【问题讨论】:

    标签: c# code-generation envdte


    【解决方案1】:

    IEnumerable&lt;T&gt; 的语法是 C# 语法,而不是 .NET 语法(它使用反引号、计数器等)。你的意思是:

    Type tableType = Type.GetType(assemblyQualifiedNameToEntity);
    Type enumerableType = typeof(IEnumerable<T>).MakeGenericType(tableType);
    

    请注意,Assembly.GetType 通常是更好的选择,因为您可以只使用命名空间限定的名称:

    Assembly asm = typeof(SomeKnownType).Assembly;
    Type tableType = asm.GetType(namespaceQualifiedNameToEntity);
    

    【讨论】:

    • 非常感谢您的回复,当您说 Assembly.GetType 是更好的选择时。您是说第二个版本可以单独使用吗?
    • 当我做 Type.GetType("Debugging.Catalog.ProductModelEntity") 时,我得到空值。我期望这是因为它是我正在使用的 DSL,并且代码生成程序集与生成代码的位置不同。它是一个动态类型
    • 你完成动态类型了吗?还是还在建设中?如果完成,那么以Assembly 开头的版本应该可以工作,但最简单的选择是在构造过程中简单地将动态类型对象保留在查找中。我已经打了这场仗 - 它不漂亮;-p
    • 我真的很纠结如何获得我的 Dynamic Type ,有什么建议吗?我有我的 CodeClass2 对象
    【解决方案2】:

    已设法使其与以下各项一起工作:

    string returnType = "System.Collections.Generic.IEnumerable<" + tableNameAsSingular + ">"; 
    CodeFunction2 finderFunction = (CodeFunction2)entityServiceClass.AddFunction("Get" + table.Name, vsCMFunction.vsCMFunctionFunction, returnType, -1, vsCMAccess.vsCMAccessPublic, null);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多