| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 1 | 2 | 3 | 4 | 5 | 6 | |
| 7 | 8 | 9 | 10 | 11 | 12 | 13 |
| 14 | 15 | 16 | 17 | 18 | 19 | 20 |
| 21 | 22 | 23 | 24 | 25 | 26 | 27 |
| 28 | 29 | 30 | 31 |
- gitea
- trayicon
- theme
- 트레이아이콘
- 젤리핀
- Resident
- Capcom
- Re
- toroisegit
- 시놀로지
- Resident Evil
- DataTable
- synology
- 깃티gpg
- CmdKey
- LogonUI
- Column
- jellyfin
- gitea설치
- unable to boot the simulator
- 깃티설치
- Header
- DataGridView
- c#
- 시놀로지깃티설치
- 깃티
- checkbox
- Gitea GPG
- gfd
- Gitea 설치
- Today
- Total
C O D I N G
캐스팅 as, is 본문
개체는 다형성이므로 기본 클래스 형식의 변수는 파생 형식을 가질 수 있습니다.
파생 형식의 메서드에 액세스하려면 값을 파생 형식으로 다시 캐스팅해야 합니다. 그러나 이러한 경우 단순한 캐스팅을 시도하려면 <xref:System.InvalidCastException>이 throw될 수 있는 위험을 감수해야 합니다.
이 때문에 C#은 및 연산자를 제공합니다. 이러한 연산자를 사용하면 예외를 throw시키지 않고 캐스트 성공 여부를 테스트할 수 있습니다.
일반적으로 캐스트가 성공하면 실제로 캐스트 값을 반환하는 as 연산자가 훨씬 효율적입니다.
is 연산자는 부울 값만 반환합니다. 따라서 이 연산자는 개체 형식을 결정하고 실제로 캐스트하지는 않는 경우에 사용할 수 있습니다.
as를 사용했을때 int, double, float등에 Null값을 넣을수 없지만
int? a = 변수면 as int?;
앞뒤로 ?를 붙여주면 변수에 null값이 들어가게 된다.
class SafeCasting { class Animal { public void Eat() { Console.WriteLine("Eating."); } public override string ToString() { return "I am an animal."; } } class Mammal : Animal { } class Giraffe : Mammal { } class SuperNova { } static void Main() { SafeCasting app = new SafeCasting(); // Use the is operator to verify the type. // before performing a cast. Giraffe g = new Giraffe(); app.UseIsOperator(g); // Use the as operator and test for null // before referencing the variable. app.UseAsOperator(g); // Use the as operator to test // an incompatible type. SuperNova sn = new SuperNova(); app.UseAsOperator(sn); // Use the as operator with a value type. // Note the implicit conversion to int? in // the method body. int i = 5; app.UseAsWithNullable(i); double d = 9.78654; app.UseAsWithNullable(d); // Keep the console window open in debug mode. System.Console.WriteLine("Press any key to exit."); System.Console.ReadKey(); } void UseIsOperator(Animal a) { if (a is Mammal) { Mammal m = (Mammal)a; m.Eat(); } } void UseAsOperator(object o) { Mammal m = o as Mammal; if (m != null) { Console.WriteLine(m.ToString()); } else { Console.WriteLine("{0} is not a Mammal", o.GetType().Name); } } void UseAsWithNullable(System.ValueType val) { int? j = val as int?; if (j != null) { Console.WriteLine(j); } else { Console.WriteLine("Could not convert " + val.ToString()); } } }
'Programming > C#' 카테고리의 다른 글
| DataSource Binding 방법 (0) | 2017.10.31 |
|---|---|
| Dictionary 탐색중 삭제하기 (0) | 2017.08.17 |
| DataGridView 스크롤시 열 고정, 구분자 (0) | 2016.12.22 |
| Enum에서 정한 Name을 index로 가져오기 (0) | 2016.12.22 |
| DataGridview 컬럼헤더 체크박스를 눌렀을때 Sel, DeSel하기 (0) | 2016.12.01 |
