Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/297.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 为事件的参数创建新对象时,此代码正确吗?_C#_Events_Garbage Collection - Fatal编程技术网

C# 为事件的参数创建新对象时,此代码正确吗?

C# 为事件的参数创建新对象时,此代码正确吗?,c#,events,garbage-collection,C#,Events,Garbage Collection,我遇到了以下C#函数: void SomeMethod(List<ISomeInterface> inputObjects) { IList<ISomeInterface> newListOfObjects = null; if (inputObjects != null) { //create a new list newListOfObjects = ne

我遇到了以下C#函数:

    void SomeMethod(List<ISomeInterface> inputObjects)
    {
        IList<ISomeInterface> newListOfObjects = null;

        if (inputObjects != null)
        {
            //create a new list
            newListOfObjects = new List<ISomeInterface>();
            //copy the input parameter into the new list
            foreach (ISomeInterface thing in inputObjects)
            {
                newListOfObjects.Add(thing);
            }
        }
        //send an event to another module with the new list as parameter
        DelegateHandler.AsyncInvoke(this.SomeEvent, newListOfObjects);
    }   
void SomeMethod(列出输入对象)
{
IList newListOfObjects=null;
if(inputObject!=null)
{
//创建一个新列表
newListOfObjects=新列表();
//将输入参数复制到新列表中
foreach(输入对象中的接口)
{
添加(事物);
}
}
//将新列表作为参数发送事件到另一个模块
DelegateHandler.AsyncInvoke(this.SomeEvent,newListOfObjects);
}   
我的问题是:是否有必要创建一个对象作为SomeEvent的参数?如果我只是将inputObjects作为参数传递给SomeEvent,会发生什么情况?

我猜垃圾收集器可能看不到对InputObject的引用,并在SomeMethod完成后将其删除。

您的问题不是很清楚,但是
AsyncInvoke
内部使用的数据结构将作为对象的根,并确保在
此操作之前不会收集该对象。SomeEvent
返回(在另一个线程上)。

无需复制列表。垃圾收集器将知道对象本身仍在使用中,因此不会对其进行垃圾收集


传递副本和原件之间的区别在于,如果传递原件,对列表的任何修改也将在调用方法中可见,否则修改仅对副本进行

当您将元素从一个列表复制到另一个列表时,您会在列表中保留相同的元素引用e原始列表(如果它们是引用类型)。

此代码似乎试图将传递给事件的列表所做的更改与原始输入列表(添加和删除对象)隔离开来,因此答案取决于调用SomeMethod后您对InputObject列表所做的操作。我同意Steve的看法。尽管我认为这种方法是不必要的,因为您可以只使用
新列表(InputObject)
InputObject.ToList()
作为参数。谢谢Steve和Ginosaji。我认为这就是他想要做的。这很有道理。谢谢。