C #에서 추가 변수를 만들지 않고 데이터 형식을 설정하고 싶습니다. 빈 변수를 만든 다음 유형을 비교하는 대신.
CustomType empty; //empty variable
CustomType RealFooBar = new CustomType("extremeFoobar", false) //custom datatype with data in it
if(RealFooBar.GetType() == empty.GetType())
//operation
차라리 다음과 같이하고 싶습니다.
CustomType RealFooBar // already has data
if(RealFooBar.GetType() == {CustomType})
//operation
이 작업을 수행하는 방법이 있습니까?
typeof(CustomType)
한 번 시도 했지만 그렇게 작동하지 않는 것 같습니다. 아니면 제대로하지 않았습니다.
당신은 사용해야 typeof
당신이 유형 사전에 (컴파일시에)을 알고 사용하는 경우 GetType
당신이하지 않는 경우에만하고 런타임에 변경합니다.
또 다른 한가지, 비교 만 필요하면 is
키워드 ref : IS 키워드를 사용할 수 있습니다 .
따라서 다음 중 하나가 작동합니다.
if(RealFooBar is string)
if(RealFooBar.GetType() == typeof(string))
편집 : 솔루션 설명 추가. 두 번째 예제가이 특정 경우에 작동하더라도 is
거의 모든 경우 에 사용하는 것이 좋습니다 . 그 이유는 두 번째 예가 "정확한 유형 비교"이고 상속을 사용하는 것을 훨씬 더 어렵게 만들기 때문입니다. 아래 예제에서 클래스에 사용할 때 어떻게 작동하는지 볼 수 있습니다.
class Foo {}
class Bar : Foo {}
var instanceOfBar = new Bar();
var instanceOfFoo = new Foo();
//works for base class as expected
if(instanceOfFoo is Foo) //true
if(instanceOfFoo is Bar) //false
if(instanceOfFoo.GetType() == typeof(Foo)) //true
if(instanceOfFoo.GetType() == typeof(Bar)) //false
//exact type checks could behave "unexpectedly" for classes that inherit
if(instanceOfBar is Foo) //true
if(instanceOfBar is Bar) //true
if(instanceOfBar.GetType() == typeof(Foo)) //false ???
if(instanceOfBar.GetType() == typeof(Bar)) //true
나는 어떤 의미에서 예기치 않게 단어를 사용하고 있는데, 미래에 상속하는 새로운 클래스가있을 때 Foo
와 이미 작성된 코드가 작동을 멈추거나 예기치 않게 동작 할 수 있다는 것을 알 수 없다는 의미 입니다.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다