我想通过一些适配器基于属性值访问类的函数。所有函数都有相同的原型(prototype)
我想这样做的方式是像这样声明一个字典:
Dictionary<key_values, Delegate_of_Functions>
其中 key_values
是一个包含标识函数的值的类,而 Delegate_of_Functions
是函数类型的委托(delegate)。
现在,我尝试执行以下操作:
Functions = new Dictionary<string, function>();
var a = from Fun in typeof(TheFunctionsContainer).GetMethods()
where Fun.GetCustomAttributes(typeof(The_Attribute), true).Length != 0
select Fun;
foreach (var c in a)
{
Functions.Add(
c.GetCustomAttributes(true).OfType<The_Attribute>().First().key,
new function(c)); // this line dose not compile
}
我的问题是:
- 如何让未编译的行编译?
- 有更好的方法吗?
最佳答案
鉴于 function
是一个委托(delegate)
delegate void function();
您可以使用 Delegate.CreateDelegate
创建委托(delegate)的方法
var Functions = new Dictionary<string, function>();
var a = typeof(TheFunctionsContainer).GetMethods().Where(f => f.GetCustomAttributes(typeof(The_Attribute), true).Any());
foreach (var c in a)
{
Functions.Add(
c.GetCustomAttributes(true).OfType<The_Attribute>().First().key,
(function)Delegate.CreateDelegate(typeof(function), c));
}
如果你想在一个实例上执行非静态方法,你必须提供你想要方法调用的实例Delegate.CreateDelegate
:
(function)Delegate.CreateDelegate(typeof(function), yourInstance, c)
或者只看 svicks 评论 :-)
关于c# - 根据属性值在 C# 中查找函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12159459/