static class を使う場合
var static_flg = BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
得たメソッドの返り値が Taskか
bool isAwaitable(MethodInfo m)
{
var rtype = m.ReturnType;
var ch = typeof(Task).ToString();
if (rtype.ToString().IndexOf(ch) == -1) return false;
return true;
}
using System;
using System.Reflection;
using System.Threading.Tasks;
using System.Collections.Generic;
using System.Linq;
public class X
{
public void hoge() { Console.WriteLine("X hoge"); }
public void hogeArg(int i){ Console.WriteLine($"X hogeArg {i}"); }
}
public static class sX
{
public static void hoge() { Console.WriteLine("sX hoge"); }
public static async Task hogeTask() { Console.WriteLine("sX hogeTask"); }
public static async Task<bool> hogeTaskBool()
{
Console.WriteLine("sX hogeTaskBool");
return true;
}
public static async Task<string> hogeTaskDelay(int ms){
await Task.Delay(ms);
var mes = $"xX hogeTaskDelay {ms}";
Console.WriteLine(mes);
return mes;
}
}
public static class Program
{
static async Task Main(string[] args)
{
/*
using System.Reflection;
using System.Threading.Tasks;
*/
//instance class
var cls = new X();
var type = cls.GetType();
var fn = type.GetMethod("hoge");
if(fn==null) return; /*notfound method*/
fn.Invoke(cls, new object[] { });
var fn1 = type.GetMethod("hogeArg");
fn1.Invoke(cls, new object[] { 9999 });
//static class
var static_flg = BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
var type2 = typeof(sX);//
var fn2 = type2.GetMethod("hoge", static_flg);
fn2.Invoke(null, new object[] { });
//task check
var fn3 = type2.GetMethod("hogeTask", static_flg);
var fn4 = type2.GetMethod("hogeTaskBool", static_flg);
Console.WriteLine(isAwaitable(fn3)); //true
Console.WriteLine(isAwaitable(fn4)); //true
Console.WriteLine("--------------");
Console.WriteLine(isAwaitable(fn)); //false
Console.WriteLine(isAwaitable(fn2)); //false
bool isAwaitable(MethodInfo m)
{
var rtype = m.ReturnType;
var ch = typeof(Task).ToString();
if (rtype.ToString().IndexOf(ch) == -1) return false;
return true;
}
//apply
var call =typeof(sX).GetMethod("hogeTaskDelay",static_flg);
if(isAwaitable(call)){
var ret = await (dynamic)call.Invoke(null,new object[]{ 5*1000 });
}
else{
var ret = (dynamic)call.Invoke(null, new object[] { 5 * 1000 });
}
}
}//class Program