C#: 如何将变量用作类型?

3

我是一名JavaScript开发者,对C#还不熟悉(所以“类型”对我来说是新的东西)。

警告“...是一个变量但被用作类型”的含义是什么?

我有以下代码写在一个叫做test的静态函数中:

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

Type type = typeof(ExcelReference) or Type type = activeCell.GetType(); - Dmitry Bychenko
2个回答

9

你可以仅对类型使用typeof,例如Type type = typeof(ExcelReference);

如果你想知道变量的类型是什么,请使用Type type = activeCell.GetType();


谢谢。你什么时候会使用 typeof()?这个页面上还有另一个答案提到了反射 - 看起来只有在我使用反射时才有用? - Zach Smith
@ZachSmith 你也可以检查参数的输入类型,例如 if(input.GetType() == typeof(string)) {...}。在这个例子中,input 的类型是 object。这不是反射,而是类型泛化。 - RusArt
我明白了,谢谢。在JS中,你会这样说:if (typeof input === 'string') {...} - Zach Smith
@ZachSmith 是的,但在C#中,input应该派生自通用基类型(object)。此外还有“类似JS”的类型dynamic。但它很慢,不建议常规使用。 - RusArt

2

实际上很容易。 typeof 用于类、接口等名称,而对于您想要的内容,您需要使用 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
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接