118

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

我现在有这样的事情:

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

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

9 回答 9

152

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.

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";

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

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

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.

To illustrate that in code:

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

Another user edited this answer to incorporate a function that appears below in the comments, a generic helper method to use type inference to get a reference to a variable's static type at run time, thanks to typeof:

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

You can use this function in the example above:

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

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

instead of

SomeMethod("String");
于 2012-07-24T16:02:40.013 回答
24

它非常简单

variable.GetType().Name

它将返回您变量的数据类型

于 2014-03-28T18:43:24.927 回答
17

一般来说,你几乎不需要进行类型比较,除非你用反射或接口做一些事情。尽管如此:

如果您知道要与之比较的类型,请使用isoras运算符:

if( unknownObject is TypeIKnow ) { // run code here

运算符执行强制转换,as如果失败则返回 null 而不是异常:

TypeIKnow typed = unknownObject as TypeIKnow;

如果您不知道类型并且只需要运行时类型信息,请使用 .GetType() 方法:

Type typeInformation = unknownObject.GetType();

在较新版本的 C# 中,您可以使用is运算符来声明变量,而无需使用as

if( unknownObject is TypeIKnow knownObject ) {
    knownObject.SomeMember();
}

以前你必须这样做:

TypeIKnow knownObject;
if( (knownObject = unknownObject as TypeIKnow) != null ) {
    knownObject.SomeMember();
}
于 2012-07-24T15:24:19.727 回答
5

只需将光标悬停在您感兴趣的成员上,然后查看工具提示 - 它会显示成员的类型:

在此处输入图像描述

于 2012-07-24T15:24:20.150 回答
4

使用 GetType() 方法

http://msdn.microsoft.com/en-us/library/system.object.gettype.aspx

于 2012-07-24T15:23:31.070 回答
3

一种选择是使用如下的辅助扩展方法:

public static class MyExtensions
{
    public static System.Type Type<T>(this T v) => typeof(T);
}

var i = 0;
console.WriteLine(i.Type().FullName);
于 2016-07-25T20:50:38.507 回答
1

GetType()方法

int n = 34;
Console.WriteLine(n.GetType());
string name = "Smome";
Console.WriteLine(name.GetType());
于 2012-07-24T15:24:12.453 回答
1

使用Object.GetType方法,这将完成工作。

如果您只想知道变量的类型:

var test = (byte)1;
Console.WriteLine(test.GetType());
于 2021-10-14T07:57:57.993 回答
0

查看执行此操作的一种简单方法

// 从控制台读取字符串

string line = Console.ReadLine(); 
int valueInt;
float valueFloat;

if (int.TryParse(line, out valueInt)) // Try to parse the string as an integer
    Console.Write("This input is of type Integer.");
else if (float.TryParse(line, out valueFloat)) 
    Console.Write("This input is of type Float.");
else
    Console.WriteLine("This input is of type string.");
于 2017-08-09T12:06:15.977 回答