开发者

Given a string denoting a type, I need to know if it's a value or reference type

开发者 https://www.devze.com 2023-04-07 14:40 出处:网络
I\'m writing a T4 template and got stuck on this. If consumers of the template write: Please generate stuff for: string myString

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?


  1. Get the corresponding instance of the Type class (i.e. Type.GetType or Assembly.GetType).

  2. Check the IsValueType property.

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 
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号