Skip to content

Instantly share code, notes, and snippets.

@st63jun
Created July 1, 2013 03:52
Show Gist options
  • Save st63jun/5898252 to your computer and use it in GitHub Desktop.
Save st63jun/5898252 to your computer and use it in GitHub Desktop.
非同期メソッドでTry-メソッドめいたものを使う
using System.Threading.Tasks;
namespace Try
{
public static class TaskExtensions
{
public static async Task<ITriable<T>> AsTriable<T>(this Task<T> task)
{
return await Triable<T>.ToTriableAsync(task);
}
}
}
using System.Threading.Tasks;
namespace Try
{
public interface ITriable<T>
{
bool TryGet(out T obj);
}
public class Triable<T> : ITriable<T>
{
private T _obj;
public Triable(T obj)
{
_obj = obj;
}
public static async Task<ITriable<T>> ToTriableAsync(Task<T> task)
{
var result = await task;
if (result == null)
return new Nothing<T>();
else
return new Triable<T>(result);
}
public bool TryGet(out T obj)
{
obj = _obj;
return true;
}
}
public class Triable
{
public static async Task<ITriable<T>> ToTriableAsync<T>(Task<T> task)
{
return await Triable<T>.ToTriableAsync(task);
}
}
public class Nothing<T> : ITriable<T>
{
public bool TryGet(out T obj)
{
obj = default(T);
return false;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment