【问题标题】:Generating code -- is there an easy way to get a proper string representation of nullable type?生成代码——有没有一种简单的方法来获得可空类型的正确字符串表示?
【发布时间】:2011-01-28 09:50:51
【问题描述】:

所以我正在构建一个应用程序,它将使用 C# 和 VB 输出(取决于项目设置)生成大量代码。

我有一个 CodeTemplateEngine,它有两个派生类 VBTemplateEngine 和 CSharpTemplateEngine。这个问题是关于根据数据库表中的列创建属性签名。使用 IDataReader 的 GetSchemaTable 方法,我收集了列的 CLR 类型,例如“System.Int32”,以及它是否为 IsNullable。但是,我想保持代码简单,而不是有一个看起来像这样的属性:

    public System.Int32? SomeIntegerColumn { get; set; }

    public Nullable<System.Int32> SomeIntegerColumn { get; set; },

使用此函数(来自我的 VBTemplateEngine)解析属性类型的位置,

    public override string ResolveCLRType(bool? isNullable, string runtimeType)
    {
        Type type = TypeUtils.ResolveType(runtimeType);
        if (isNullable.HasValue && isNullable.Value == true && type.IsValueType)
        {
            return "System.Nullable(Of " + type.FullName + ")";
            // or, for example...
            return type.FullName + "?";
        }
        else
        {
            return type.FullName;
        }
    },

我想生成一个更简单的属性。我讨厌从无到有构建类型字符串的想法,我宁愿有类似的东西:

    public int? SomeIntegerColumn { get; set; }

是否有任何内置的东西,例如在 VBCodeProvider 或 CSharpCodeProvider 类中,可以以某种方式为我解决这个问题?

或者有没有办法从像System.Nullable'1[System.Int32] 这样的类型字符串中获取int? 的类型别名?

谢谢!

更新:

Found something 可以,但我仍然对类型全名到其别名的那种类型的映射持谨慎态度。

【问题讨论】:

    标签: c# vb.net code-generation


    【解决方案1】:

    您可以使用 CodeDom 对泛型类型的支持和 GetTypeOutput 方法来做到这一点:

    CodeTypeReference ctr;
    if (/* you want to output this as nullable */)
    {
      ctr = new CodeTypeReference(typeof(Nullable<>));
      ctr.TypeArguments.Add(new CodeTypeReference(typeName));
    }
    else
    {
      ctr = new CodeTypeReference(typeName);
    }
    string typeName = codeDomProvider.GetTypeOutput(ctr);
    

    这将尊重特定于语言的类型关键字,例如 C# int 或 VB Integer,但它仍会为您提供 System.Nullable&lt;int&gt; 而不是 int?

    【讨论】:

    • 这会让我走到一半,这比我开始的要好。今晚我会试试,让你知道我的想法。谢谢!
    • 虽然这种方法可能并不适合每个人,但它适合我并回答了我“有没有其他方法”的问题。谢谢!
    【解决方案2】:

    这里有两个问题:

    1. System.Int32 具有 C# 别名 int,这是您喜欢的。
    2. System.Nullable 可以在 C# 中使用 ? 符号表示,您更喜欢这样。

    .NET Framework 中没有包含在将类型名称转换为字符串时将这些考虑在内的方法。你将不得不自己动手。

    【讨论】:

    • 我就是这么想的。感谢您的快速回复。
    • 我考虑编写一些代码,但从你的帖子来看,你似乎已经想通了。
    • CodeDomProvider.GetTypeOutput 方法考虑了#1。尽管据我所知,您对 #2 的看法是正确的。
    猜你喜欢
    • 2012-01-21
    • 2012-06-16
    • 1970-01-01
    • 2011-01-26
    • 2010-09-26
    • 1970-01-01
    • 2022-11-10
    • 1970-01-01
    • 2010-12-05
    相关资源
    最近更新 更多