我想知道当前的委托签名。怎么找出委托返回void?
特别是我想分类“行动”和“Func”deleagte。
一样,如果目前的代表是动作,运行操作,并返回电流值,
如果FUNC,运行FUNC和FUNC的返回结果。
我想知道当前的委托签名。怎么找出委托返回void?
特别是我想分类“行动”和“Func”deleagte。
一样,如果目前的代表是动作,运行操作,并返回电流值,
如果FUNC,运行FUNC和FUNC的返回结果。
要检查委托是否返回void,你可以检查
bool isVoid = myDelegate.Method.ReturnType == typeof(void);
要具体测试的委托是否是Action
,您可以使用
bool isActionT1_T2 = myDelegate.GetType().GetGenericTypeDefinition() == typeof(Action<,>);
这将匹配任何Action<T1, T2>
(有两个泛型类型参数)。您可以对Func<T1, RetType>
以及其他参数进行相同的操作。
不知道这是最好或唯一途径,但如果你有型你可以看看的.Invoke
方法:
Type type = ...
if(type.IsSubclassOf(typeof(Delegate)))
{
var method = type.GetMethod("Invoke");
foreach(var arg in method.GetParameters())
{
Console.WriteLine(arg.Name + ": " + arg.ParameterType.ToString());
}
Console.WriteLine("returns: " + method.ReturnType.ToString())
}
的.ReturnType
将是你的情况typeof(void)
。
如果你有委托的实例,你可以做同样的与委托本身.Method
属性:
Delegate instance = ...
var method = instance.Method;
foreach(var arg in method.GetParameters())
{
Console.WriteLine(arg.Name + ": " + arg.ParameterType.ToString());
}
Console.WriteLine("returns: " + method.ReturnType.ToString());
重:
例如,如果当前的代表是动作,则运行动作并返回当前值,
您可以特殊情况:
if(instance is Action) {
((Action)instance)();
} else {
//...
}
然而,你可能需要使用DynamicInvoke
很多,如果处理任意的代表。
你可能想是这样的:
static void InspectDelegate(object obj)
{
if (!(obj is Delegate del))
return;
var returnType = del.Method.ReturnType.Name;
var parameters = del.Method.GetParameters();
Dictionary<string, string> argNames =
parameters.ToDictionary(a => a.Name, b => b.ParameterType.Name);
if (obj is Action<string, int>)
del.DynamicInvoke("foo", 2);
}
static void Main(string[] args)
{
Action<string, int> act = (x, y) => { Console.WriteLine("x={0}, y= {1}", x, y); };
InspectDelegate(act);
}
使用字符串梅辛是这样做的可怕的方式;如果有人给你一些不通用的东西('delInfo [1]'将会失败),它也会出错。 –
我放弃了_horrible_部分。 –
什么是del?在if(!(obj是Delegate del)) –