Generating code — is there an easy way to get a proper string representation of nullable type?

前端 未结 2 1067
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-15 15:11

So I\'m building an application that is going to do a ton of code generation with both C# and VB output (depending on project settings).

I\'ve got a CodeTemplateEngi

相关标签:
2条回答
  • 2021-01-15 15:41

    You can do this using CodeDom's support for generic types and the GetTypeOutput method:

    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);
    

    This will respect language-specific type keywords such as C# int or VB Integer, though it will still give you System.Nullable<int> rather than int?.

    0 讨论(0)
  • 2021-01-15 15:48

    There are two issues here:

    1. System.Int32 has the C# alias int, which you prefer.
    2. System.Nullable can be indicated using a ? symbol in C#, which you prefer.

    There are no methods included with the .NET Framework to take these into account when converting the type name to a string. You are going to have to roll your own.

    0 讨论(0)
提交回复
热议问题