public interface IBar {
}
public class Bar : IBar {
}
public class Bar2 : IBar {
}
public interface IFoo {
Task Get(T o) where T : IBar;
}
public
Because Task
derives from Task
you can await on just that, once the task is awaited you can use reflection to safely access the .Result
property via reflection.
Once you have the result you will either need to store it in a IBar
and use the methods and properties on that or cast to the specific type after testing to use the type specific methods.
Here is a full MCVE of it
using System;
using System.Reflection;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Test().Wait();
Console.ReadLine();
}
static async Task Test()
{
var foo = new Foo();
var bar2 = new Bar2();
object resultObject = await CallGetByReflection(foo, bar2);
IBar result = (IBar)resultObject;
result.WriteOut();
//or
if (resultObject is Bar)
{
((Bar)resultObject).Something();
}
else if (resultObject is Bar2)
{
((Bar2)resultObject).SomethingElse();
}
}
private static async Task
UPDATE: Here is a extension method to simplify the process
public static class ExtensionMethods
{
public static async Task
This turns CallGetByReflection
in to
private static Task
UPDATE 2: Here is a new extension method that works with any awaitable type instead of only tasks by using dynamic
and GetAwaiter()
public static class ExtensionMethods
{
public static async Task