2011-04-11 2 views

답변

6

시도 인덱서 object 반환하면

string s = (i["property"] ?? "none").ToString(); 
2

다음

(i["property"] ?? (object)"none").ToString() 

하거나 :

(i["property"] ?? "none").ToString() 

string 경우

i["property"] ?? "none" 
+1

+1이 특별한 경우에는'object ?? 문자열 '은 이미 캐스트없이 올바르게 넓혀졌습니다. (i [ "property"]'*가 객체이지만 ... 지정되지 않았습니다.) –

2

재미를위한 대안.

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; } 
} 
+0

+1 게시 할 시간입니다. 그러나 이와 같은 접근법의 한 가지 문제점은 일부 연산자 ('&&','||',''??','? :', 등)가 게으른 것입니다. 이 경우 Coalesce 함수에 대한 인수는 열심히 평가됩니다. 여기에 상관 없지만 그것은 중요 할 수 있습니다. ''none ''이 실제로'Foo (x)'라고 상상해보십시오. 이것은 λ/func를 사용하여 처리 할 수 ​​있지만 C# 구문은 마술/자동 해제를 수행하지 않으므로 신속하게 성가 시게 될 수 있습니다. –

관련 문제