我是C#的新手,来自Javascript背景(所以'打字'对我来说很新鲜。)
警告“......是变量但是像类型一样使用”是什么意思?
我在名为test
的静态函数中有以下代码:
var activeCell = new ExcelReference(1, 1);
Type type = typeof(activeCell);
答案 0 :(得分:8)
您只能将typeof
用于某个类型,例如Type type = typeof(ExcelReference);
如果您想知道此变量的类型,请使用Type type = activeCell.GetType();
答案 1 :(得分:1)
示例:
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
}
}