I have a T4 template where I would like to generate a .cs file.
I have an array of System.Data.DataColumn , which I would like to use as private variables in my generated code file.
I use ColumnName as the name of the variable, Value as the value of the variable, and DataType as the variable data type.
I am thinking about how to initialize certain variables in this case:
ColumnName = "col1" ColumnValue = "text" DatType = System.String
I would like to see the output: private System.String col1 = "text";
Variable definition in T4 template:
private <#= DataType.ToString() #> <#= ColumnName #> = "<=# ColumnValue #>"
I am thinking of writing a helper method that will return a variable initialization string for common data types. Something like:
public string ValueInitializerString { get { string valueString; if (this.DataType == typeof(int)) { valueString = this.Value.ToString(); } else if (this.DataType == typeof(string)) { valueString = string.Format("\"{0}\"", this.Value); } else if (this.DataType == typeof(DateTime)) { DateTime dateTime = (DateTime)this.Value; valueString = string.Format("new DateTime({0}, {1}, {2}, {3}, {4}, {5}, {6})", dateTime.Year, dateTime.Month, dateTime.Day, dateTime.Hour, dateTime.Minute, dateTime.Second, dateTime.Millisecond); } else { throw new Exception(string.Format("Data type {0} not supported. ", this.DataType)); } return valueString; } }
If someone did something like this, could you advise if this is a good idea or can this be done in a more convenient way? Maybe I should read something?
Sergejs
source share