Created
July 1, 2013 03:52
-
-
Save st63jun/5898252 to your computer and use it in GitHub Desktop.
非同期メソッドでTry-メソッドめいたものを使う
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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