Skip to main content
 首页 » 编程设计

C# 构造函数作为方法的参数

2024年02月05日8开发

我是 C# 脚本的新手。

我正在阅读一些代码,在一个类方法中有一个函数调用以添加到名为 Listeners 的 Dictionary 实例中,如下所示:

public class ...... 
{ 
    private Dictionary<string, List<Component>> Listeners =  
        new Dictionary<string, List<Component>>(); 
 
    public void AddListener(Component Listener, string NotificationName) 
    { 
        // Add listener to dictionary 
        if (!Listeners.ContainsKey(NotificationName)) 
            Listeners.Add (NotificationName, new List<Component>()); 
 
        // Add object to listener list for this notification 
        Listeners[NotificationName].Add(Listener); 
    } 
} 

现在,似乎对 Listeners.Add 的调用有一个构造函数调用

new List<Component>() 

作为参数。

我做对了吗?

请您参考如下方法:

Now , it seems the call to Listeners.Add ...

你的意思是不是调用Listeners[NotificationName].Add我假设。

... has a constructor call new List<Component>() as an argument. Am I getting it right ?

是的,调用有两个参数。第一个参数是当前方法的形参,第二个参数是对象创建表达式。这些参数在运行时的值 将是对字符串的引用 和对新创建对象的引用。

这里的操作顺序是,首先评估接收者,然后生成那些参数值,然后是Add。方法将被调用,这些值复制到它的形式参数中,接收者值用作this .

代码的意思是“我有一个从名称到列表的映射;如果这个映射没有特定名称的映射,则创建一个从名称到空列表的映射东西”。第二个Add调用然后将单个元素添加到该列表中。

来自对另一个答案的评论:

I cannot get my hands on the instance reference outside that function call

好吧,您确实在紧接着的下一行,通过再次从 map 中读取它来获得它。但是如果没有允许您通过评估另一个表达式来获取该值的设备,就像您在这里所做的那样,您是正确的。该表达式只是产生一个值;它不会将任何名称与您以后可以使用的名称相关联。如果您想这样做,那么您需要创建一个局部变量。