Как узнать тип переменной C#
Введение
Для определения типа переменной в C# существует функция GetType()
Пример
Небольшая демонстрация
using System; public class MyBaseClass { } public class MyDerivedClass: MyBaseClass { } public class Test { public static void Main() { MyBaseClass myBase = new MyBaseClass(); MyDerivedClass myDerived = new MyDerivedClass(); object o = myDerived; MyBaseClass b = myDerived; Console.WriteLine("mybase: Type is {0}", myBase.GetType()); Console.WriteLine("myDerived: Type is {0}", myDerived.GetType()); Console.WriteLine("object o = myDerived: Type is {0}", o.GetType()); Console.WriteLine("MyBaseClass b = myDerived: Type is {0}", b.GetType()); } } // The example displays the following output: // mybase: Type is MyBaseClass // myDerived: Type is MyDerivedClass // object o = myDerived: Type is MyDerivedClass // MyBaseClass b = myDerived: Type is MyDerivedClass
int n1 = 12; int n2 = 82; long n3 = 12; Console.WriteLine("n1 and n2 are the same type: {0}", Object.ReferenceEquals(n1.GetType(), n2.GetType())); Console.WriteLine("n1 and n3 are the same type: {0}", Object.ReferenceEquals(n1.GetType(), n3.GetType())); // The example displays the following output: // n1 and n2 are the same type: True // n1 and n3 are the same type: False
Результат
n1 and n2 are the same type: True n1 and n3 are the same type: False
В других языках
- Си : такой функции нет.
-
C++
:
похожую задачу решает функция
typeid()
Читать статью: «Как определить тип переменной C++»
-
Go
:
функция
typeof
доступна из библиотеки reflect
Читать статью: «Как определить тип переменной Go»
-
Java
:
оператор
instanceof
-
JavaScript
:
эту задачу решает
typeof()
Читать статью: «Как определить тип переменной JavaScript»
-
PHP
:
есть функция с практически таким же названием -
gettype()
Читать статью: «Как определить тип переменной PHP»
-
Python
:
аналогичная функция
type()
и немного другая функция
isinstance()
с помощью которой можно решить эту же задачу.
Читать статью: «Как определить тип переменной Python»
Автор статьи: Андрей Олегович