Domanda

I'm in the immediate window in Visual Studio. There's a variable p. How can I deduce the type of the variable p?

I tried p.GetType() but that returns the type of object p. In my case, this is a very specific type (eg. sometimes ChessPlayer, sometimes TennisPlayer). I'd like to know the type of the variable, ie. the type that determines what methods are available on the variable p.


Edit: I think this is a reasonable thing to want to do. I am trying to inspect the variable p but I don't know it is! Normally in Visual Studio I just hover the mouse on the variable and it tells me its type, or I type . and the autocomplete lists its methods. However none of that works in the immediate window, all I have is this variable p I don't know what it is or what I can do with it :(

È stato utile?

Soluzione 2

Surprised this was so difficult, in the end I wrote this method, which seems to give the right answer.

public static class Extensions
{
    public static Type GetVariableType<T>(this T instance)
    {
        return typeof(T);
    }
}

Example usage:

void Main()
{
    IList x = new List<int>{};
    x.GetVariableType().Dump();
}

Prints System.Collections.IList

Altri suggerimenti

c# provides many ways for this :)

For the exact copy of specific type you need to do this

if (p.GetType() == typeof(YourDesiredType))

If you want to know whether p is an instance of yourdesiredtype then

if (p is YourDesiredType)

or you can try this

YourDesiredType ydp = p as YourDesiredType;

As in this case (as i'm not sure that it is possible in your scenario)when OP wants to know the compile type Then I would only recommend to use a generic list for this

Because by keeping Type safe list , everyone can easily keep track for its type

As an alternative to using the immediate window, if you only want to see the type of the variable, you can simply add a variable watch and check the type in the watch window.

System.Object.GetType()

This will return you the type of the variable because this class in the top of hierarchy from which every class is derived.

you can also check typeof function to get the exact type of the given instance.

I think you might need this

if (p is ChessPlayer)
{
    ChessPlayer cp = (ChessPlayer)p;

    //Use ChessPlayer methods
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top