如何在 C# 中获取变量的数据类型? [英] How can I get the data type of a variable in C#?

查看:251
本文介绍了如何在 C# 中获取变量的数据类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何找出某个变量所持有的数据类型?(例如 int、string、char 等)

How can I find out what data type some variable is holding? (e.g. int, string, char, etc.)

我现在有这样的事情:

private static void Main()
{
   var someone = new Person();
   Console.WriteLine(someone.Name.typeOf());
}

public class Person
{
    public int Name { get; set; }
}

推荐答案

其他答案对这个问题提供了很好的帮助,但有一个重要而微妙的问题,他们都没有直接解决.C#中有两种考虑类型的方法:静态类型运行时类型.

Other answers offer good help with this question, but there is an important and subtle issue that none of them addresses directly. There are two ways of considering type in C#: static type and run-time type.

静态类型是源代码中变量的类型.因此,它是一个编译时概念.这是您将鼠标悬停在开发环境中的变量或属性上时在工具提示中看到的类型.

Static type is the type of a variable in your source code. It is therefore a compile-time concept. This is the type that you see in a tooltip when you hover over a variable or property in your development environment.

运行时类型是内存中对象的类型.因此,它是一个运行时概念.这是 GetType() 方法返回的类型.

Run-time type is the type of an object in memory. It is therefore a run-time concept. This is the type returned by the GetType() method.

对象的运行时类型经常不同于保存或返回它的变量、属性或方法的静态类型.例如,你可以有这样的代码:

An object's run-time type is frequently different from the static type of the variable, property, or method that holds or returns it. For example, you can have code like this:

object o = "Some string";

变量的静态类型是object,但在运行时,变量的referent类型是string.因此,下一行将打印System.String";到控制台:

The static type of the variable is object, but at run time, the type of the variable's referent is string. Therefore, the next line will print "System.String" to the console:

Console.WriteLine(o.GetType()); // prints System.String

但是,如果您将鼠标悬停在开发环境中的变量 o 上,您将看到类型 System.Object(或等效的 object代码>关键字).

But, if you hover over the variable o in your development environment, you'll see the type System.Object (or the equivalent object keyword).

对于值类型变量,例如intdoubleSystem.Guid,您知道运行时类型将始终与静态类型相同,因为值类型不能作为其他类型的基类;值类型保证是其继承链中派生最多的类型.对于密封引用类型也是如此:如果静态类型是密封引用类型,则运行时值必须是该类型的实例或 null.

For value-type variables, such as int, double, System.Guid, you know that the run-time type will always be the same as the static type, because value types cannot serve as the base class for another type; the value type is guaranteed to be the most-derived type in its inheritance chain. This is also true for sealed reference types: if the static type is a sealed reference type, the run-time value must either be an instance of that type or null.

相反,如果变量的静态类型是抽象类型,那么保证静态类型和运行时类型会不同.

Conversely, if the static type of the variable is an abstract type, then it is guaranteed that the static type and the runtime type will be different.

用代码来说明:

// int is a value type
int i = 0;
// Prints True for any value of i
Console.WriteLine(i.GetType() == typeof(int));

// string is a sealed reference type
string s = "Foo";
// Prints True for any value of s
Console.WriteLine(s == null || s.GetType() == typeof(string));

// object is an unsealed reference type
object o = new FileInfo("C:\f.txt");
// Prints False, but could be true for some values of o
Console.WriteLine(o == null || o.GetType() == typeof(object));

// FileSystemInfo is an abstract type
FileSystemInfo fsi = new DirectoryInfo("C:\");
// Prints False for all non-null values of fsi
Console.WriteLine(fsi == null || fsi.GetType() == typeof(FileSystemInfo));


另一位用户编辑了此答案以合并出现在评论下方的函数,这是一种通用的辅助方法,可在运行时使用类型推断来获取对变量静态类型的引用,这要归功于 typeof:

Type GetStaticType<T>(T x) => typeof(T);

你可以在上面的例子中使用这个函数:

You can use this function in the example above:

Console.WriteLine(GetStaticType(o)); // prints System.Object

但是这个函数的效用有限,除非你想保护自己免受重构.当您编写对 GetStaticType 的调用时,您已经知道 o 的静态类型是对象.你还不如写

But this function is of limited utility unless you want to protect yourself against refactoring. When you are writing the call to GetStaticType, you already know that o's static type is object. You might as well write

Console.WriteLine(typeof(object)); // also prints System.Object!

这让我想起了我开始当前工作时遇到的一些代码,比如

This reminds me of some code I encountered when I started my current job, something like

SomeMethod("".GetType().Name);

代替

SomeMethod("String");

这篇关于如何在 C# 中获取变量的数据类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆