gpt4 book ai didi

c# - 如何在 C# 中获取变量的数据类型?

转载 作者:IT王子 更新时间:2023-10-29 03:39:26 26 4
gpt4 key购买 nike

我如何找出某个变量保存的数据类型? (例如 int、string、char 等)

我现在有这样的东西:

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

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

最佳答案

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

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

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

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

object o = "Some string";

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

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

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

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

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

用代码来说明:

// 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);

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

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

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

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

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

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

代替

SomeMethod("String");

关于c# - 如何在 C# 中获取变量的数据类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11634079/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com