【发布时间】:2016-10-16 07:51:52
【问题描述】:
我正在使用 IronPython,并且我知道如何将我的类中的方法公开到脚本的范围:
m_scope.SetVariable("log", new Action<string>(Log));
public void Log(string a)
{
Console.WriteLine(a);
}
但是,不是每次我想使用反射来加快进程时都调用SetVariable。所以,我创建了一个名为ScriptMethodAttribute的属性:
public sealed class ScriptMethodAttribute : Attribute
{
public string Name { get; private set; }
public ScriptMethodAttribute(string name)
{
Name = name;
}
}
这样,我可以在我的类中定义方法供脚本使用,如下所示:
[ScriptMethod("log")]
public void Log(string a)
{
Console.WriteLine(a);
}
现在我想在每个使用此属性的方法上调用 SetVariable 来加快进程。但是,这似乎不起作用。
这是一个返回Tuple<ScriptMethodAttribute, MethodInfo列表的实用方法。
public static IEnumerable<Tuple<TAttribute, MethodInfo>> FindMethodsByAttribute<TAttribute>()
where TAttribute : Attribute
{
return (from method in AppDomain.CurrentDomain.GetAssemblies()
.Where(assembly => !assembly.GlobalAssemblyCache)
.SelectMany(assembly => assembly.GetTypes())
.SelectMany(type => type.GetMethods())
let attribute = Attribute.GetCustomAttribute(method, typeof(TAttribute), false) as TAttribute
where attribute != null
select new Tuple<TAttribute, MethodInfo>(attribute, method));
}
这位于我脚本的类构造函数中:
foreach (var a in Reflector.FindMethodsByAttribute<ScriptMethodAttribute>())
{
Action action = (Action)Delegate.CreateDelegate(typeof(Action), this, a.Item2);
m_scope.SetVariable(a.Item1.Name, action);
}
我收到以下异常:
System.ArgumentException: Cannot bind to the target method because its signature or security transparency is not compatible with that of the delegate type.
我猜是因为我必须在 Action 构造函数中包含所需的类型,但我不知道如何从 MethodInfo 类中获取它们。
【问题讨论】:
标签: c# reflection ironpython