简体   繁体   English

是否有C#等同于python的type()函数?

[英]Is there a C# equivalent to python's type() function?

I am learning C# and have a very basic background in Python where I was familiar with the type() function where the data type of a variable can be returned via: 我正在学习C#并且具有Python的非常基础的背景知识,我熟悉type()函数 ,该函数可以通过以下方式返回变量的数据类型:

type(myVariable)

Is there a C# equivalent to this function? 是否有C#等效于此功能?

I am asking in the context of wanting to use such a function on a C# variable that has been created using var eg: 我是在想要对使用var eg创建的C#变量上使用这样的功能的情况下询问的:

var myNewVariable = "Hello!"

I am using explicit data types in general eg: 我一般使用显式数据类型,例如:

string myNewString = "Hello!"

But I am just wondering what data type a variable created using var defaults to and thought something similar to type() would be a good way to check out what was happening ' under the hood ` so to speak. 但我只是想知道,使用可变创造了什么数据类型var默认,并认为类似的东西type()将是检查了什么引擎盖下发生'的好办法`这么说。

You can try using GetType() method: 您可以尝试使用GetType()方法:

Type myType = myVariable.GetType();

For instance 例如

String typeName = "My String".GetType().Name; // <- "String"

You have couple of options here 您在这里有几个选择

  1. typeof. 类型。 typeof takes a type name (which you specify at compile time). typeof采用类型名称(您在编译时指定)。
  2. GetType gets the runtime type of an instance. GetType获取实例的运行时类型。

Example

B a = new B();
a.GetType() == typeof(B) 

Note: a is an instance of an object B . 注意: a是对象B的实例。 Whereas B is a type. 而B是一种类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM