如何在 C# 中获取变量的数据类型?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11634079/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I get the data type of a variable in C#?
提问by Limeni
How can I find out what data type some variable is holding? (e.g. int, string, char, etc.)
如何找出某个变量所持有的数据类型?(例如 int、string、char 等)
I have something like this now:
我现在有这样的事情:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Testing
{
class Program
{
static void Main()
{
Person someone = new Person();
someone.setName(22);
int n = someone.getName();
Console.WriteLine(n.typeOf());
}
}
class Person
{
public int name;
public void setName(int name)
{
this.name = name;
}
public int getName()
{
return this.name;
}
}
}
采纳答案by phoog
There is an important and subtle issue that none of them addresses directly. There are two ways of considering type in C#: static typeand run-time type.
有一个重要而微妙的问题,他们都没有直接解决。在 C# 中有两种考虑类型的方法:静态类型和运行时类型。
Static typeis 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.
静态类型是源代码中变量的类型。因此,它是一个编译时概念。这是您将鼠标悬停在开发环境中的变量或属性上时在工具提示中看到的类型。
You can obtain static type by writing helper generic method to let type inference take care of it for you:
您可以通过编写辅助泛型方法来获取静态类型,让类型推断为您处理它:
Type GetStaticType<T>(T x) { return typeof(T); }
Run-time typeis the type of an object in memory. It is therefore a run-time concept. This is the type returned by the GetType()method.
运行时类型是内存中对象的类型。因此,它是一个运行时概念。这是GetType()方法返回的类型。
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 referentis string. Therefore, the next line will print "System.String" to the console:
变量的静态类型是object,但在运行时,变量所指对象的类型是string。因此,下一行将打印“System.String”到控制台:
Console.WriteLine(o.GetType()); // prints System.String
But, if you hover over the variable oin your development environment, you'll see the type System.Object(or the equivalent objectkeyword). You also see the same using our helper function from above:
但是,如果您将鼠标悬停o在开发环境中的变量上,您将看到类型System.Object(或等效object关键字)。您还可以使用上面的辅助函数看到相同的内容:
Console.WriteLine(GetStaticType(o)); // prints System.Object
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.
对于值类型变量,例如int, double, System.Guid,您知道运行时类型将始终与静态类型相同,因为值类型不能作为另一种类型的基类;值类型保证是其继承链中派生最多的类型。对于密封引用类型也是如此:如果静态类型是密封引用类型,则运行时值必须是该类型的实例或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));
回答by Stephen Oberauer
Use the GetType() method
使用 GetType() 方法
http://msdn.microsoft.com/en-us/library/system.object.gettype.aspx
http://msdn.microsoft.com/en-us/library/system.object.gettype.aspx
回答by Shyju
GetType()method
GetType()方法
int n=34;
Console.WriteLine(n.GetType());
string name="Smome";
Console.WriteLine(name.GetType());
回答by Dai
Generally speaking, you'll hardly ever need to do type comparisons unless you're doing something with reflection or interfaces. Nonetheless:
一般来说,除非您使用反射或接口做一些事情,否则您几乎不需要进行类型比较。尽管如此:
If you know the type you want to compare it with, use the isor asoperators:
如果您知道要与之比较的类型,请使用is或as运算符:
if( unknownObject is TypeIKnow ) { // run code here
The asoperator performs a cast that returns null if it fails rather than an exception:
该as运营商进行演员,其中返回null如果失败,而不是一个例外:
TypeIKnow typed = unknownObject as TypeIKnow;
If you don't know the type and just want runtime type information, use the .GetType() method:
如果您不知道类型而只想要运行时类型信息,请使用 .GetType() 方法:
Type typeInformation = unknownObject.GetType();
In newer versions of C#, you can use the isoperator to declare a variable without needing to use as:
在较新版本的 C# 中,您可以使用is运算符来声明变量而无需使用as:
if( unknownObject is TypeIKnow knownObject ) {
knownObject.SomeMember();
}
Previously you would have to do this:
以前,您必须这样做:
TypeIKnow knownObject;
if( (knownObject = unknownObject as TypeIKnow) != null ) {
knownObject.SomeMember();
}
回答by Sergey Berezovskiy
Just hold cursor over member you interested in, and see tooltip - it will show memeber's type:
只需将光标悬停在您感兴趣的成员上,然后查看工具提示 - 它会显示成员的类型:


回答by Sagar Chavan
Its Very simple
它非常简单
variable.GetType().Name
it will return your datatype of your variable
它将返回您的变量的数据类型
回答by Acerby
One option would be to use a helper extension method like follows:
一种选择是使用如下的辅助扩展方法:
public static class MyExtensions
{
public static System.Type Type<T>(this T v)=>typeof(T);
}
var i=0;
console.WriteLine(i.Type().FullName);
回答by Kiran Solkar
check out one of the simple way to do this
查看执行此操作的一种简单方法
// Read string from console
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.");
}

