簡體   English   中英

對象之間的引用

[英]References between objects

我已經嘗試了好幾天了。

我有三個班級,我們稱它們為“城市”,“房屋”,“房間”:

class City
{
    List<House> Houses { get; set; }
    string Name { get; set; }
}

class House
{
    List<Room> Rooms { get; set; }
    string Name { get; set; }
}

class Room
{
    string Name { get; set; }
}

因此,這里有一個擁有很多房屋的城市。 房屋擁有房間。

舉例來說,假設我得到一個房間對象,該對象的名稱(在整個系統中通過“城市”->“房屋”->“房間”分組)

我如何能夠從我擁有的那個Room對象中引用City-objects Name變量?

就像做“ Room.House.City.Name”的一些神奇方法一樣

我真的希望您了解我要問的問題,最近幾天一直讓我發瘋。

為了使之成為可能,您必須在類中添加其他類似父類的引用:

class City
{
    List<House> Houses { get; set; }
    string Name { get; set; }
}

class House
{
    List<Room> Rooms { get; set; }
    string Name { get; set; }
    City City { get; set; }
}

class Room
{
    string Name { get; set; }
    House House { get; set; }
}

更新資料

因為我認為沒有城市沒有房屋的房子和沒有房屋的房間的機會不大,所以我將構造函數添加到HouseRoom類中,以將它們綁定到父母:

class House
{
    public House(City city)
    {
        City = city;

    }
    List<Room> Rooms { get; set; }
    string Name { get; set; }
    City City { get; set; }
}

class Room
{
    public Room(House house)
    {
        House = house;
    }
    string Name { get; set; }
    House House { get; set; }
}

您可以將House屬性添加到您的房間,將City屬性添加到House如下所示:

class House
{
    List<Room> Rooms { get; set; }
    string Name { get; set; }
    public City City { get; set; }
 }

class Room
{
    string Name { get; set; }
    public House House { get; set; }
}

例如,當您添加一些房屋和房間時:

    City myCity = new City();
    House myHouse = new House { City = myCity, Name = "myHome" };
    Room myRoom = new Room { House = myHouse, Name = "myRoom" };
    myHouse.Rooms = new List<Room>();    
    myHouse.Rooms.Add(myRoom);
    myCity.Houses = new List<House>();        
    myCity.Houses.Add(myHouse);
    // here you can use:
    myRoom.House.City.Name

但這不是那么優雅,很難添加新的房屋和房間。此外,我將添加一些方法來簡化它,例如在房屋類中:

class House 
{
     public void AddRoom(Room room)
     {
        room.House = this;
        if (Rooms == null)
            Rooms = new List<Room>();
        Rooms.Add(room);
     }
}

然后,我不需要定義這樣的房間:

Room myRoom = new Room { House = myHouse, Name = "myRoom" };

代替:

myHouse.AddRoom(new Room { Name = "myRoom" });

您必須更改類以包含對其父級的引用,例如

class Room
{
    House House { get; set; }
    string Name { get; set; }
}

class House
{
    List<Room> Rooms { get; set; }
    string Name { get; set; }
    City City { get; set; }
}

通常,您無法從屬性導航到其容器。 僅當在“房間”對象中還具有“房屋”之類的屬性,並且確保將“房間”分配為“房屋”時,還可以在“房間”中設置“房屋”屬性,才有可能。

但是,您可以使用一些LINQ來獲取城市名稱,如下所示:

var cityWithSomeRoom = cities.Where(c = > c.Houses.Contains(h => h.Rooms.Contains(r => r.ReferenceEquals(someRoom))).FirstOrDefault();
cityWithSomeRoom.Name ; // this is your name

someRoom是您要查找所在城市的Room實例。 另外,請確保不要將同一房間對象添加到多個房屋中,因為ReferenceEquals會找到很多候選對象。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM