我是C#的新手,来自JavaScript背景(因此'typing'对我来说是很新的)。
警告是什么……是一个变量,但像一种类型一样使用"?
我在称为 test
的静态函数中具有以下代码:
var activeCell = new ExcelReference(1, 1);
Type type = typeof(activeCell);
您只能与类型一起使用typeof
,例如Type type = typeof(ExcelReference);
如果您想知道该变量是什么类型,则使用Type type = activeCell.GetType();
实际上很容易。 typeof 与类,接口等名称一起使用,同时您需要的是 getType function。
示例:
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
}
}