![](/img/trans.png)
[英]What does the statement “to qualify the use of a type in that namespace” mean in C#
[英]C#: What does it mean to use a variable like a type?
我是C#的新手,来自Java的背景(因此“键入”对我来说是很新的)。
警告“ ...是变量,但像类型一样使用”是什么意思?
我在称为test
的静态函数中包含以下代码:
var activeCell = new ExcelReference(1, 1);
Type type = typeof(activeCell);
您只能将typeof
与类型一起使用,例如Type type = typeof(ExcelReference);
如果您想知道此变量是什么类型,请使用Type type = activeCell.GetType();
实际上很容易。 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
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.