Code generation - is there an easy way to get the correct NULL string representation?

So, I am creating an application that collects a ton of code generation with C # and VB outputs (depending on the project settings).

I have a CodeTemplateEngine, with two derived classes VBTemplateEngine and CSharpTemplateEngine. This question is about creating property-based column signatures in a database table. Using the IDataReader GetSchemaTable method, I collect the CLR type of the column, for example, "System.Int32", and whether it is IsNullable. However, I would like to keep the code simple and instead of a property that looks like this:

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

or

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

where the property type will be resolved using this function (from my 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; } }, 

I would like to create a simpler property. I hate the idea of ​​building a type string from nothing, and I would prefer something like:

  public int? SomeIntegerColumn { get; set; } 

Is there anything built in anywhere, for example, in the VBCodeProvider or CSharpCodeProvider classes that somehow take care of this for me?

Or is there a way to get an alias of type int? from a type string, such as System.Nullable'1[System.Int32] ?

Thanks!

UPDATE:

found something to do this, but I'm still afraid of this type of matching full type names with their aliases.

+2
source share
2 answers

You can do this using CodeDom 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 take into account language type keywords such as C # int or VB Integer , although it will still give you System.Nullable<int> and not int? .

+4
source

There are two problems here:

  • System.Int32 has the C # int alias that you prefer.
  • System.Nullable can be specified with the ? in C # which you prefer.

There are no methods included in the .NET Framework to take them into account when converting a type name to a string. You will have to collapse yourself.

+2
source

Source: https://habr.com/ru/post/889933/


All Articles