-
-
Save dmdymov/bc3663d8994ec1f4048e151ec32fe03a to your computer and use it in GitHub Desktop.
SOExample2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
double d = 1.3; | |
string s = (string)d; //ошибка компиляции, компилятор знает, что привести double к string нельзя | |
object d1 = 1.3; | |
string s1 = (string)d1; //ошибка исполнения, привести double к string все так же нельзя, но узнаем мы об этом уже во время исполнения | |
object d2 = 1.3; | |
string s2 = d2 as string; //хотя привести double к string все так же нельзя, не выбрасывает исключение, а присваивает s null | |
//главный пример использования - в метод приходит object, реальный тип мы не знаем, при этом знаем тип, с которым хотим работать | |
private void MethodName(object arg) | |
{ | |
var obj = arg as DesiredType; | |
if (obj != null) | |
{ | |
// делаем что-нибудь с obj | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment