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

前端 未结 2 1079
佛祖请我去吃肉
佛祖请我去吃肉 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 rather than int?.

提交回复
热议问题