我是一名JavaScript开发者,对C#还不熟悉(所以“类型”对我来说是新的东西)。
警告“...是一个变量但被用作类型”的含义是什么?
我有以下代码写在一个叫做test
的静态函数中:
var activeCell = new ExcelReference(1, 1);
Type type = typeof(activeCell);
你可以仅对类型使用typeof
,例如Type type = typeof(ExcelReference);
如果你想知道变量的类型是什么,请使用Type type = activeCell.GetType();
typeof()
?这个页面上还有另一个答案提到了反射 - 看起来只有在我使用反射时才有用? - Zach Smithif(input.GetType() == typeof(string)) {...}
。在这个例子中,input
的类型是 object
。这不是反射,而是类型泛化。 - RusArtif (typeof input === 'string') {...}
- Zach Smithinput
应该派生自通用基类型(object)。此外还有“类似JS”的类型dynamic
。但它很慢,不建议常规使用。 - RusArt实际上很容易。 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
}
}
Type type = typeof(ExcelReference)
orType type = activeCell.GetType();
- Dmitry Bychenko