더 쉬운 방법이 있나요?C#에서 이렇게 쉬운 방법이 있습니까? (null-coalescing type question)
string s = i["property"] != null ? "none" : i["property"].ToString();
통지 IT 및 널 병합 (??) 사이의 차이는 없다 - 널 값 (?? OP의 제 피연산자)를 반환하기 전에 액세스되는 것으로한다.
더 쉬운 방법이 있나요?C#에서 이렇게 쉬운 방법이 있습니까? (null-coalescing type question)
string s = i["property"] != null ? "none" : i["property"].ToString();
통지 IT 및 널 병합 (??) 사이의 차이는 없다 - 널 값 (?? OP의 제 피연산자)를 반환하기 전에 액세스되는 것으로한다.
시도 인덱서 object
반환하면
string s = (i["property"] ?? "none").ToString();
다음
(i["property"] ?? (object)"none").ToString()
하거나 :
(i["property"] ?? "none").ToString()
string
경우
i["property"] ?? "none"
을
재미를위한 대안.
void Main()
{
string s1 = "foo";
string s2 = null;
Console.WriteLine(s1.Coalesce("none"));
Console.WriteLine(s2.Coalesce("none"));
var coalescer = new Coalescer<string>("none");
Console.WriteLine(coalescer.Coalesce(s1));
Console.WriteLine(coalescer.Coalesce(s2));
}
public class Coalescer<T>
{
T _def;
public Coalescer(T def) { _def = def; }
public T Coalesce(T s) { return s == null ? _def : s; }
}
public static class CoalesceExtension
{
public static string Coalesce(this string s, string def) { return s ?? def; }
}
+1 게시 할 시간입니다. 그러나 이와 같은 접근법의 한 가지 문제점은 일부 연산자 ('&&','||',''??','? :', 등)가 게으른 것입니다. 이 경우 Coalesce 함수에 대한 인수는 열심히 평가됩니다. 여기에 상관 없지만 그것은 중요 할 수 있습니다. ''none ''이 실제로'Foo (x)'라고 상상해보십시오. 이것은 λ/func를 사용하여 처리 할 수 있지만 C# 구문은 마술/자동 해제를 수행하지 않으므로 신속하게 성가 시게 될 수 있습니다. –
+1이 특별한 경우에는'object ?? 문자열 '은 이미 캐스트없이 올바르게 넓혀졌습니다. (i [ "property"]'*가 객체이지만 ... 지정되지 않았습니다.) –