2014-12-19 71 views
1

我正在.NET(C#)中处理日历应用程序。让几个对象的属性指向同一个对象

通常,用户从复选框列表中检查姓名,然后他可以在日历上看到每个人的所有事件。

我有例如CalendarWeek对象,CalendarEvent对象和CalendarTableCell对象。

我需要他们所有的人都有一个列表作为一个属性,但它必须是所有的列表。

我想我应该用这个指针,我没有真正理解我找到的指南,所以我想要一些帮助。

+0

添加列表属性,每个类,创建一个列表实例,并指定要列出每个列表属性对象你有(CalendarWeek等)。然后他们将指向相同的列表对象。 – user469104

+0

你是否熟悉'ref'关键词...? – MethodMan

+0

你是否熟悉单身? – DidIReallyWriteThat

回答

0

我需要他们所有人都有一个列表作为一个属性,但它必须是在他们所有相同的列表。

如果您需要多个对象来使用同一个列表,那绝对没有问题:创建一个列表对象,并将它传递给需要使用它的类的构造函数。像C#中的所有类一样(而不是struct和原语)List<T>和其他集合是通过引用对象。这意味着在你的情况下,如果你将List<T>分配给不同对象中的实例字段,这些字段将引用相同的列表。

class CalendarEvent { 
    public List<Stuff> ListOfStuff {get;private set;} 
    public CalendarEvent(List<Stuff> myList) { 
     ListOfStuff = myList; 
    } 
} 
class CalendarWeek { 
    public List<Stuff> ListOfStuff {get;private set;} 
    public CalendarWeek(List<Stuff> myList) { 
     ListOfStuff = myList; 
    } 
} 
... 
// Create a list 
List<Stuff> theList = new List<Stuff>(); 
// Add things to it 
theList.Add(...); 
// Make CalendarEvent and CalendarWeek 
var ce = new CalendarEvent(theList); 
var cw = new CalendarWeek(theList); 
// At this point ce.ListOfStuff and cw.ListOfStuff have the same list 
相关问题