C#:使用类型变量是什么意思?

时间:2016-12-27 09:39:06

标签: c# types

我是C#的新手,来自Javascript背景(所以'打字'对我来说很新鲜。)

警告“......是变量但是像类型一样使用”是什么意思?

我在名为test的静态函数中有以下代码:

var activeCell = new ExcelReference(1, 1);
Type type = typeof(activeCell);

2 个答案:

答案 0 :(得分:8)

您只能将typeof用于某个类型,例如Type type = typeof(ExcelReference);

如果您想知道此变量的类型,请使用Type type = activeCell.GetType();

答案 1 :(得分:1)

事实上非常容易。 typeof 与Class,Interface等名称一起使用,同时根据您的需要,您需要 GetType 功能。

示例:

public class MyObject
{
    public static Type GetMyObjectClassType()
    {
        return typeof(MyObject);
    }
    public static Type GetMyObjectInstanceType(MyObject someObject)
    {
        return someObject.GetType();
    }

    public static Type GetAnyClassType<GenericClass>()
    {
        return typeof(GenericClass);
    }
    public static Type GetAnyObjectInstanceType(object someObject)
    {
        return someObject.GetType();
    }

    public void Demo()
    {
        var someObject = new MyObject();
        Console.WriteLine(GetMyObjectClassType()); // will write the type of the class MyObject
        Console.WriteLine(GetMyObjectInstanceType(someObject)); // will write the type of your instance of MyObject called someObject
        Console.WriteLine(GetAnyClassType<MyObject>()); // will write the type of any given class, here MyObject
        Console.WriteLine(GetAnyClassType<System.Windows.Application>()); //  will write the type of any given class, here System.Windows.Application
        Console.WriteLine(GetAnyObjectInstanceType("test")); // will write the type of any given instance, here some string called "test"
        Console.WriteLine(GetAnyObjectInstanceType(someObject)); // will write the type of any given instance, here your instance of MyObject called someObject
    }
}