【问题标题】:How do I create a class that inherits from another and passes a type parameter in CodeDom?如何创建一个继承自另一个类并在 CodeDom 中传递类型参数的类?
【发布时间】:2009-08-28 16:58:49
【问题描述】:

这是我希望生成的类声明的样子:

public sealed partial class Refund : DataObjectBase<Refund>
 {
}

}

这段代码(截断):

targetClass = new CodeTypeDeclaration(className);
            targetClass.IsClass = true;
            targetClass.TypeAttributes =
                TypeAttributes.Public | TypeAttributes.Sealed;
            targetClass.IsPartial = true; //partial so that genn'ed code can be safely modified
            targetClass.TypeParameters.Add(new CodeTypeParameter{ Name=className});
            targetClass.BaseTypes.Add(new CodeTypeReference { BaseType = "DataObjectBase", Options = CodeTypeReferenceOptions.GenericTypeParameter });

产生这个类声明:

public sealed partial class Refund<Refund> : DataObjectBase
 {
}

我做错了什么?

【问题讨论】:

    标签: c# codedom type-parameter


    【解决方案1】:

    我认为 BaseType 的以下字符串应该可以解决问题(未经测试):

    "DataObjectBase`1[[Refund]]"
    

    您可能需要为Refund 提供一个完全限定的名称,至少包括程序集名称:

    "DataObjectBase`1[[Refund, RefundAssembly]]"
    

    然后你应该删除targetClass.TypeParameters.Add(...)这一行。

    【讨论】:

    • 正确的行最终是 targetClass.BaseTypes.Add(new CodeTypeReference { BaseType = "DataObjectBase`1[Refund]", Options = CodeTypeReferenceOptions.GenericTypeParameter });
    【解决方案2】:

    如果你使用Expressions to CodeDOM 可能是

    var cls = Define.Class("Refund", 
       TypeAttributes.Public | TypeAttributes.Sealed, true)
       .Inherits(CodeDom.TypeRef("DataObjectBase","Refund"))
    

    【讨论】:

      猜你喜欢
      • 2023-03-26
      • 1970-01-01
      • 1970-01-01
      • 2015-05-08
      • 2014-11-22
      • 1970-01-01
      • 2014-10-08
      • 2021-08-23
      • 1970-01-01
      相关资源
      最近更新 更多