2017-03-04 117 views
0

我在想一種創建鏈接或引用字符串列表的方法。我的情況是,我正在創建ARP表,我需要保存捕獲響應消息的接口的IP(作爲字符串)。接口的IP地址保存在列表<String>中。C#列表中的鏈接元素

ARP_Table_entry(System.Net.IPAddress host_ip_addr, System.Net.NetworkInformation.PhysicalAddress host_mac_addr, int position) 
    { 
     this.host_ip_addr = host_ip_addr; 
     this.host_mac_addr = host_mac_addr; 
     this.time = System.DateTime.Now.Ticks/TimeSpan.TicksPerMillisecond; 
     this.local_inter = ??; 
    } 

我不想做什麼,是分配local_inter SMT像list.ElementAt(0),因爲當我在界面上更改IP地址(表得到更新瓦特/新的),值條目不會改變 - 我必須做foreach每一個條目(不壞,但是...)

而是我正在尋找解決方案,這將「鏈接」該特定列表元素local_inter參數 - 所以在列表中更改IP將導致每個包含舊的條目的自動更新。

+0

基本上你想要將你的列表元素綁定到你的'local_inter'上? – dbraillon

+0

是的,就是這個想法。 – MMMaroko

回答

0

如果你能控制代碼ARP_Table_entry只是讓local_inter屬性,從那個神祕的列表返回值:

class ARP_Table_entry 
{ 
    List<string> mysteriousList; 
    int pos; 
    public ARP_Table_entry(List<string> mysteriousList, int pos,...) 
    { 
     this.mysteriousList = mysteriousList; 
     this.pos = pos; 
     ... 
    } 

    // TODO: add null check/position verification as needed 
    string local_inter => mysteriousList[pos]; 
    // or {get { return mysteriousList[pos];} for C# 5 and below 
    ... 

您還可以使用Func<string>類型或local_inter如果你想使用的字段出於某種原因:

class ARP_Table_entry 
{ 
    public Func<string> local_inter; 
    ... 

    public ARP_Table_entry(List<string> mysteriousList, int pos,...) 
    { 
     local_inter =() => mysteriousList[pos]; 
     ... 
    } 

請注意,這兩種方法都不能保護您完全不用originalMysteriousList = new List<string>()替換列表。

另一種選擇是讓更復雜的類型存儲將通知其更改的IP列表(類似於ObesrvableCollection)並更新集合中的更改字段。