Typeof考虑类而不是变量

时间:2016-11-22 07:28:54

标签: c# asp.net variables typeof

有一个字符串变量,其名称与类相同。 Console.WriteLine“在我显示时显示字符串内容,但在我尝试typeof()时指向该类。为什么?

class Fun { }
class MyFun
{
    static void Main()
    {
        string Fun = "hello, world";
        string s = Fun;
        Type t = typeof(Fun);
        Console.WriteLine(s);
        Console.WriteLine(t);
    }
}

2 个答案:

答案 0 :(得分:2)

由于Fun本地变量,而不是类型名称(例如string),正确的语法是

 Type t = Fun.GetType();

或(如果你想要typeof):

 Type t = typeof(string);

有关详细信息,请参阅https://msdn.microsoft.com/en-us/library/58918ffs.aspxhttps://msdn.microsoft.com/en-us/library/system.object.gettype.aspx

答案 1 :(得分:0)

因为你不能typeof变量,只能是一种类型。因此,课程被选中。

对于变量,您可以访问object.GetType()

Type t = Fun?.GetType();