C#에는 훌륭한 연산자 '??'가 있습니다. 그것은 인생을 훨씬 단순하게 만든다. (foo != null)? foo : default
을 쓰는 대신 foo ?? default
을 쓸 수 있습니다. 이 연산자를 클래스 구성원에게 적용하는 간단한 방법이 있습니까? 상황이 (foo != null)? foo.bar : default
일까요?사용할 수 있습니까 ?? 반원들에 대한 연산자?
UPD :이 기능은 다음과 같습니다 필요로 할 때 상황 : :
이string a = (someVeryLongVariableName != null)? someVeryLongVariableName : ""; // Long way
string a = someVeryLongVariableName ?? ""; // Shorter with same result
string a = (someVeryLongVariableName != null)? someVeryLongVariableName.bar : ""; // What's the shorter way in this case?
upd2가 :
if (foo is MyClass) bar1 = (foo as MyClass).SpecificMember;
if (foo is OneMoreClass) bar2 = (foo as OneMoreClass).AnotherSpecificMember;
if (foo is MyFavoriteClass) bar3 = (foo as MyFavoriteClass).YetAnotherMember;
그것은 경우 멋진 수 있습니다 OK 나는 조금 expalin 것 나는 이것들을 단축시킬 수있다.
bar1 = (foo as MyClass).SpecificMember ?? null;
어쩌면 짧지는 않지만 foo를 MyClass로 한 번만 캐스팅하고 명시 적으로 바를 기본값으로 초기화합니다. 그리고 가장 중요한 것은 더 멋지게 보입니다.
간단한 쓰지 않는 것 (foo! = null)? foo.bar : 기본 ?? –
무엇? 네가 훨씬 더 간단해질 수 있을지 모르겠다. 뭔가 놓친 거니? – IAbstract
upd2에 내 게시물 – Poma