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

最后都变了- 提交于 2019-12-01 10:58:09

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?.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!