简体   繁体   English

如何使用roslyn获得泛型类的运行时类型?

[英]How to get a run-time type of generic class using roslyn?

For example I have the following type: 例如,我有以下类型:

public class MyClass<T>
{
    public T Prop { get; }
}

Or let say I have the following method: 或者说我有以下方法:

private static void Method<T>() 
{
     //how I can get a real type of <T>
}

How can I get a run-time type of generic class using roslyn ? 如何使用roslyn获得泛型类的运行时类型? I mean real type of <T> 我的意思是<T>实型

static void Main(string[] args)
{
    // here I need to get int
    var m = new MyClass<int>();

    // here I need to get object
    var m1 = new MyClass<object>();
}

If you have the MyClass syntax tree and you want to get the concrete type or instantiated type of ITypeParameterSymbol T , the simple answer is, you can't do it with Roslyn. 如果您拥有MyClass语法树,并且想要获取ITypeParameterSymbol T的具体类型或实例化类型,那么简单的答案是,您不能使用Roslyn做到这一点。

If you mean how to get the type from instantiation like this new MyClass<int>() , the answer is: 如果您是说如何像这样的new MyClass<int>()这样从实例中获取类型,则答案是:

var genericType = // the ObjectCreationExpressionSyntax from type GenericNameSyntax
var typArg = genericType.TypeArgumentList.Arguments.First();
var type = model.GetSymbolInfo(typeArg).Symbol // this is your concrete type

You can also parse the IdentifierName or TypeSyntax in the TypeArgument but it's syntactically, not semantically. 您也可以解析IdentifierNameTypeSyntaxTypeArgument但它的语法,语义不。

Update 更新资料

Please explain from which point of view you want to get the info about the run-time type. 请从哪个角度解释您要获取有关运行时类型的信息。

As I wrote, if you hold the syntax tree of MyClass<T> (in your example) you can't get any info. 如我所写,如果您拥有MyClass<T>的语法树(在您的示例中),您将无法获得任何信息。 Roslyn can tell you that is a generic type but that it. Roslyn可以告诉您这是一个泛型类型,但是它却是。 The only way to get this info is in run-time (for example, if you in debug mode and you set a breakpoint somewhere in this class and inspect the type of T in the watch window). 获取此信息的唯一方法是在运行时(例如,如果您处于调试模式,并且在此类的某个位置设置了断点并在监视窗口中检查T的类型)。

If you want to get the type from instanciated syntax like var m = new MyClass<int>() in your example, it's easy as I answered. 如果您想从示例中的实例化语法(例如var m = new MyClass<int>()中获取类型,则很容易回答。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM