Given a string denoting a type, I need to know if it's a value or reference type
I'm writing a T4 template and got stuck on this. If consumers of the template write:
Please generate stuff for: string myString
I need to generate
if (myString != null)
{
DoStuffWith(myString)
}
Whereas if they write
Please generate stuff for: int myInt
I need to generate simply
DoStuffWith(myInt)
And this needs to work with custom value/reference types too.
If I forced the template consumers to write System.String myString or System.Int32开发者_如何学运维 myInt, I imagine this could be done without trouble; there's presumably some GetTypeFromFullTypeName method hiding in the framework somewhere. But I don't want to make them do that.
Any ideas on how my T4 template could get at this information, so I could conditionally generate the right code?
Get the corresponding instance of the
Typeclass (i.e.Type.GetTypeorAssembly.GetType).Check the
IsValueTypeproperty.
The number of types with "short names" is very limited, they're actually C# keywords. So you can use a case statement, e.g. case "string": return typeof (string);
You'll also need some rules for ?, and for finding a specific concrete version of generic classes (recursion will be helpful). Don't try to translate int? into System.Nullable``1[System.Int32], instead use typeof(System.Nullable<>).MakeGenericType(FindType("int")).
You could emit the null check always, even for value types. This is not a compiler error, but produces a warning which you could suppress:
#pragma warning disable CS0472
if (myInt != null)
{
DoStuffWith(myInt)
}
#pragma warning restore CS0472
加载中,请稍侯......
精彩评论