【问题标题】:C# check if ref List<> contents have changed [duplicate]C# 检查 ref List<> 内容是否已更改 [重复]
【发布时间】:2017-01-19 18:07:11
【问题描述】:

比如说我在课堂上有这个:

List<int> myIntegerList;

public MyClass(ref List<int> intList)
{
    myIntegerList= intList;
}

这在我的主要课程中:

List<int> myIntegerList = new List<int>();
MyClass myNewClass;

for (int i = 0; i < 10; i++)
{
    myIntegerList .Add(Random.Next(0, 100));
}

myNewClass = new MyClass(ref IntegerList);

如果引用的List&lt;int&gt; 的内容已更改,是否有一种简单的方法可以检查myNewClass 对象?例如如果列表中的任何随机整数发生变化,则在 myNewClass 对象中引发一个事件。

【问题讨论】:

  • 使用ObservableCollection 而不是List。另外,不要使用ref。在 C# 中,myIntegerList已经是对对象的引用。只需传递参考。
  • 您不需要使用ref。只有当您想将传入的参数分配给其他东西并更改您传入的变量时,您才需要它。

标签: c# list events ref


【解决方案1】:

List&lt;T&gt; 不会这样做,但ObservableCollection&lt;T&gt; 会。另外,不要在构造函数中使用ref 参数;任何引用类实例的 C# 变量都是引用。 ref 类类型的参数是一个引用一个引用,你不想要也可能不想考虑。

using System.Collections.ObjectModel;

public class MyClass
{
    private ObservableCollection<int> _integerList;

    //  Do not make this a ref parameter, it's a reference already
    public MyClass(ObservableCollection<int> intList)
    {
        _integerList = intList;
        _integerList.CollectionChanged += _integerList_CollectionChanged;
    }

    private void _integerList_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
    {
        //  Do stuff here in response to changed values in the list. 

        //  Now back to the reference thing again: int is immutable.
        //  You can't change it, you can only replace it with another 
        //  int. This event will be raised when you do that. 
        //
        //  If the objects in the ObservableCollection are class 
        //  instances rather than ints, they're mutable. You can 
        //  change their properties without replacing them. 
        //  ObservableCollection cannot know when that happens, so 
        //  it can't tell you. 
        //
        //  In that case, you'd need the class to implement 
        //  INotifyPropertyChanged. That's a different can of worms, 
        //  but it's a manageable one. 
    }
}

...

ObservableCollection<int> ints = new ObservableCollection<int>();
MyClass myNewClass;
var r = new Random();

for (int i = 0; i < 10; i++)
{
    ints.Add(r.Next(0, 100));
}

myNewClass = new MyClass(ints);

【讨论】:

  • 必须更新 4 年前的代码库才能使其正常工作,但这是值得的。谢谢!另一个快速的问题,有没有办法使用 ref 来确保从 List 中删除一个项目时,它也会从另一个 List 中删除?基本上我想让一个 List 包含对另一个 List 中的项目的引用,并且能够同时删除两者而无需使用事件。
  • @GryffDavid 它绝对必须是两个不同的集合对象吗?可以做到,但我更愿意通过共享一个集合来做到这一点。
  • 情况有点奇怪。是为了游戏。第二个列表只需要包含原始列表中的一些项目,原始列表中的相同项目可能最终会在任何时候被删除,我需要更改以回显到第二个列表。
  • @GryffDavid 我会查看过滤后的 CollectionView:msdn.microsoft.com/en-us/library/…
【解决方案2】:

使用 ObservableCollection..查看以下链接以获取更多参考

ObservableCollection msdn

【讨论】:

    猜你喜欢
    • 2013-02-22
    • 2011-10-10
    • 1970-01-01
    • 2014-11-17
    • 2023-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-08
    相关资源
    最近更新 更多