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");
I’m not sure if my answer would help.
The short answer is, you don’t really need/want to know the type of a variable to use it.
If you need to give a type to a static variable, then you may simply use auto.
In more sophisticated case where you want to use «auto» in a class or struct, I would suggest use template with decltype.
For example, say you are using someone else’s library and it has a variable called «unknown_var» and you would want to put it in a vector or struct, you can totally do this:
template <typename T>
struct my_struct {
int some_field;
T my_data;
};
vector<decltype(unknown_var)> complex_vector;
vector<my_struct<decltype(unknown_var)> > simple_vector
Hope this helps.
EDIT: For good measure, here is the most complex case that I can think of: having a global variable of unknown type. In this case you would need c++14 and template variable.
Something like this:
template<typename T> vector<T> global_var;
void random_func (auto unknown_var) {
global_var<decltype(unknown_var)>.push_back(unknown_var);
}
It’s still a bit tedious but it’s as close as you can get to typeless languages. Just make sure whenever you reference template variable, always put the template specification there.
Введение | |
typeid().name() | |
В других языках | |
Другие статьи о С++ |
Введение
Для определения типа переменной в C++ существует функция
typeid().name()
из библиотеки
typeinfo
которую нужно предварительно подключить с помощью
#include <typeinfo>
typeid().name()
Небольшая демонстрация
#include <string>
#include <iostream>
#include <typeinfo>
int main()
{
// Создадим четыре переменные разных типов
int int_var = 1;
float float_var = 1.0;
char char_var = '0';
std::string str1 = "www.heihei.ru";
// Выведем на экран результат работы typeid
std::cout << typeid(int_var).name() << std::endl;
std::cout << typeid(float_var).name() << std::endl;
std::cout << typeid(char_var).name() << std::endl;
std::cout << typeid(str1).name() << std::endl;
return 0;
}
Результат
int
float
char
class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >
C:Usersaosourcerepostypeidx64Debugtypeid.exe (process 132920) exited with code 0.
Press any key to close this window . . .
Все четыре типа определены.
В других языках
-
Си
: такой функции нет.
-
C#
:
есть похожая функцияGetType()
-
Go
:
функцияtypeof
доступна из библиотеки reflect
Читать статью: «Как определить тип переменной Go»
-
Java
:
операторinstanceof
-
JavaScript
:
эту задачу решаетtypeof()
Читать статью: «Как определить тип переменной JavaScript»
-
PHP
:
эту задачу решаетgettype()
Читать статью: «Как определить тип переменной PHP»
-
Python
:
аналогичная функцияtype()
и немного другая функция
isinstance()
с помощью которой можно решить эту же задачу.
Читать статью: «Как определить тип переменной Python»
Development на C++ | |
Перегрузка функций | |
-c: Компиляция | |
Разбиение кода на части | |
Вектор | |
Указатели | |
Классы | |
SFML | |
Тетрис на C++ с библиотекой SFML2 | |
SDL | |
Массив Структур | |
Решение задач на C++ | |
Как создать пустую строку в C++ | |
Запросы к REST API на C++ | |
Ошибки C++ | |
Make |
(PHP 4, PHP 5, PHP 7, PHP
gettype — Get the type of a variable
Description
gettype(mixed $value
): string
Parameters
-
value
-
The variable being type checked.
Return Values
Possible values for the returned string are:
-
"boolean"
-
"integer"
-
"double"
(for historical reasons"double"
is
returned in case of a float, and not simply
"float"
) -
"string"
-
"array"
-
"object"
-
"resource"
-
"resource (closed)"
as of PHP 7.2.0 -
"NULL"
-
"unknown type"
Changelog
Version | Description |
---|---|
7.2.0 |
Closed resources are now reported as 'resource (closed)' .Previously the returned value for closed resources were 'unknown type' .
|
Examples
Example #1 gettype() example
<?php
$data
= array(1, 1., NULL, new stdClass, 'foo');
foreach (
$data as $value) {
echo gettype($value), "n";
}?>
The above example will output
something similar to:
integer double NULL object string
See Also
- get_debug_type() — Gets the type name of a variable in a way that is suitable for debugging
- settype() — Set the type of a variable
- get_class() — Returns the name of the class of an object
- is_array() — Finds whether a variable is an array
- is_bool() — Finds out whether a variable is a boolean
- is_callable() — Verify that a value can be called as a function from the current scope.
- is_float() — Finds whether the type of a variable is float
- is_int() — Find whether the type of a variable is integer
- is_null() — Finds whether a variable is null
- is_numeric() — Finds whether a variable is a number or a numeric string
- is_object() — Finds whether a variable is an object
- is_resource() — Finds whether a variable is a resource
- is_scalar() — Finds whether a variable is a scalar
- is_string() — Find whether the type of a variable is string
- function_exists() — Return true if the given function has been defined
- method_exists() — Checks if the class method exists
Anonymous ¶
1 year ago
Same as for "boolean" below, happens with integers. gettype() return "integer" yet proper type hint is "int".
If your project is PHP8+ then you should consider using get_debug_type() instead which seems to return proper types that match used for type hints.
Как в C++ программно узнать тип переменной?
Был вчера вопросик, а я не ответил впохыхах.
Коротко: для этого уже в стандарте C++98 есть оператор typeid:
#include <iostream> #include <typeinfo> int main() { int var = 5; std::cout << typeid(var).name(); std::cin.get(); return 0; }
Подробнее: посмотрим, как работает typeid
со встроенными и с определёнными пользователем типами данных (прежде всего, классами).
Прилагаемый маленький листинг из консоли Visual Studio 2015, думаю, хорошо показывает суть дела.
#include <iostream> #include <typeinfo> using namespace std; class Base {}; //Класс class Derived : public Base {}; //Класс-потомок class PolyBase { virtual void Member() {} }; //Полиморфный класс-предок в виртуальным методом class PolyDerived : public PolyBase {}; //Потомок полиморфного класса typedef int new_int; //Определели новый тип через typedef int main() { cout << boolalpha; //Чтобы печатать true/false //Простые скалярные типы: cout << typeid(int).name() << " and " << typeid(new_int).name() << endl; cout << "int == new_int? "; cout << (typeid(int) == typeid(new_int)) << 'n'; //true //Предок и потомок: cout << typeid(Base).name() << " and " << typeid(Derived).name() << endl; cout << "Base == Derived? "; cout << (typeid(Base) == typeid(Derived)) << 'n'; //false //Не-полиморфные объекты, доступ через указатель: Base* ptrBase = new Derived(); cout << typeid(Base).name() << " and " << typeid(*ptrBase).name() << endl; cout << "Base == *ptrBase? "; cout << (typeid(Base) == typeid(*ptrBase)) << 'n'; //true //Полиморфные объекты, доступ через указатель: PolyBase* ptrPolyBase = new PolyDerived(); cout << typeid(PolyBase).name() << " and " << typeid(*ptrPolyBase).name() << endl; cout << "PolyBase == *ptrPolyBase? "; cout << (typeid(PolyBase) == typeid(*ptrPolyBase)) << 'n'; //false cin.get(); return 0; }
14.03.2018, 10:31 [9858 просмотров]
К этой статье пока нет комментариев, Ваш будет первым