그래, 내가 ContentFrom 모드도 실제로 원했던 걸로 알았 기 때문에, 원래의 것보다 샘플을 번역 해주었습니다. 답변
일반적으로 다음과 같은 패러다임을 사용합니다. 검색 여기에 특정 방법을 교체하고 당신은 지금 당신의 목적을 위해 v!=null
임의로 '재미'할 수있는 방법
IEnumerable<T> ValueSources()
{
yield return _value?? _alternative;
yield return SimpleCalculationFromCache();
yield return ComplexCalculation();
yield return PromptUIInputFallback("Please help by entering a value for X:");
}
T EffectiveValue { get { return ValueSources().FirstOrDefault(v => v!=null); } }
참고가 :).평가는 계산이 완료되지 않습니다 때 _value 또는 _alternative는 '재미'로 설정되어 있는지 확인합니다 방법도 게으른
참고 여기
값이 금형에 샘플을 넣어에서 내 최초의 시도이다. 실제로 많은 독립 실행 형 C# exe 파일로 컴파일되도록 배관을 어떻게 추가했는지 유의하십시오.
using System.Collections.Generic;
using System.Linq;
using System;
using T=System.String;
namespace X { public class Y
{
public static void Main(string[]args)
{
var content = Sources().FirstOrDefault(c => c); // trick: uses operator bool()
}
internal protected struct Content
{
public T Value;
public ContentFrom Mode;
//
public static implicit operator bool(Content specimen) { return specimen.Mode!=ContentFrom.None && null!=specimen.Value; }
}
private static IEnumerable<Content> Sources()
{
// mock
var Request = new { QueryString = new [] {"id"}.ToDictionary(a => a) };
if (!String.IsNullOrEmpty(Request.QueryString["id"]))
yield return new Content { Value = GetContent(Convert.ToInt64(Request.QueryString["id"])), Mode = ContentFrom.Query };
if (DefaultId != null)
yield return new Content { Value = GetContent((long) DefaultId), Mode = ContentFrom.Default };
yield return new Content();
}
public enum ContentFrom { None, Query, Default };
internal static T GetContent(long id) { return "dummy"; }
internal static readonly long? DefaultId = 42;
} }
왜 ContentMode가 'Content'클래스의 속성이 아닙니까? '콘텐츠'클래스의 일부로 만들면 코드가 더 짧아지고 더 읽기 쉬워 질 수 있습니다. 그리고 ContentFrom.None 열거 형이 필요하지 않습니다. NULL 콘텐츠 객체는 해당 열거 형의 논리를 대체합니다. – SolutionYogi
'Content'는 제 3 자 API에서 가져온 것이기 때문에. 하나는이 프로젝트에 사용해야합니다 ... 나는 다른 제안들 중 하나처럼 그것을 포장 할 수 있다고 생각합니다. – Andy