Skip to main content
 首页 » 编程设计

c#之如何基于包含其名称的字符串执行方法

2024年02月13日18hnrainll

我有一个包含多个方法的对象,在它之外我有一个字符串列表,其中每个字符串值都是方法的名称。我想根据名称执行方法。从经验来看,在 python 中它非常简单。在 c# 中,我假设它应该由我认为的委托(delegate)来完成。或者使用 methodInvoking? 我想忽略对此的反射(reflection)。

在 python 中,你可以将方法存储为对象,因为它是一个对象。

def a(): 
    return 1 
def b(): 
    return 2 
def c(): 
    return 3 
 
l= [a,b,c] 
 
for i in l: 
    print i() 

输出将是:

>>> 1 
>>> 2 
>>> 3 

请您参考如下方法:

如果你想忽略反射,你可以为每个方法调用创建一个委托(delegate)并存储在字典中。

操作方法如下:

var methods = new Dictionary<string, Action >() { 
            {"Foo", () => Foo()}, 
            {"Moo", () => Moo()}, 
            {"Boo", () => Boo()} 
        }; 
 
methods["Foo"].Invoke();