이것은 어리석은 질문이지만이 코드를 사용하여 무언가가 특정 유형인지 확인할 수 있습니다 …
if (child is IContainer) { //....
“NOT”인스턴스를 확인하는 더 우아한 방법이 있습니까?
if (!(child is IContainer)) { //A little ugly... silly, yes I know...
//these don't work :)
if (child !is IContainer) {
if (child isnt IContainer) {
if (child aint IContainer) {
if (child isnotafreaking IContainer) {
예, 그렇습니다 … 바보 같은 질문 …
코드가 어떻게 생겼는지에 대한 의문이 있기 때문에 메소드 시작시 간단히 리턴됩니다.
public void Update(DocumentPart part) {
part.Update();
if (!(DocumentPart is IContainer)) { return; }
foreach(DocumentPart child in ((IContainer)part).Children) {
//...etc...
답변
if(!(child is IContainer))
갈 유일한 연산자입니다 ( IsNot
연산자 가 없습니다 ).
이를 수행하는 확장 메소드를 빌드 할 수 있습니다.
public static bool IsA<T>(this object obj) {
return obj is T;
}
그리고 그것을 사용하여 :
if (!child.IsA<IContainer>())
그리고 당신은 당신의 주제를 따를 수 있습니다 :
public static bool IsNotAFreaking<T>(this object obj) {
return !(obj is T);
}
if (child.IsNotAFreaking<IContainer>()) { // ...
업데이트 (OP의 코드 스 니펫 고려) :
나중에 값을 실제로 캐스팅하기 때문에 as
대신 사용할 수 있습니다 .
public void Update(DocumentPart part) {
part.Update();
IContainer containerPart = part as IContainer;
if(containerPart == null) return;
foreach(DocumentPart child in containerPart.Children) { // omit the cast.
//...etc...
답변
이 방법으로 할 수 있습니다 :
object a = new StreamWriter("c:\\temp\\test.txt");
if (a is TextReader == false)
{
Console.WriteLine("failed");
}
답변
왜 다른 것을 사용하지 않습니까?
if (child is IContainer)
{
//
}
else
{
// Do what you want here
}
친숙하고 간단합니다.
답변
올바른 방법 이지만 “NOT”인스턴스를 확인하는보다 우아한 방법을 만들기 위해 확장 방법 세트를 작성할 수 있습니다.
public static bool Is<T>(this object myObject)
{
return (myObject is T);
}
public static bool IsNot<T>(this object myObject)
{
return !(myObject is T);
}
그럼 당신은 쓸 수 있습니다 :
if (child.IsNot<IContainer>())
{
// child is not an IContainer
}
답변
아직 언급되지 않았습니다. 작동하고 사용하는 것보다 낫다고 생각합니다.!(child is IContainer)
if (part is IContainer is false)
{
return;
}
is
구문 : expr is constant
, 여기서 expr은 평가할 표현식이고 constant는 테스트 할 값입니다.
답변
추한? 동의하지 않습니다. 유일한 다른 방법 (개인적으로 이것이 “더 추악하다고 생각합니다”) :
var obj = child as IContainer;
if(obj == null)
{
//child "aint" IContainer
}
답변
is
당신은 아무것도 할 수 있도록 부울 결과에 운영자 평가하여, 당신은 그렇지 않으면 부울에 할 수있을 것입니다. 부정하려면 !
연산자를 사용하십시오 . 이것을 위해 왜 다른 연산자를 원하십니까?
