[英]C# uncommon access to object's properties
我有幾個主要對象。 它們每個都有從屬對象列表。 每個從屬對象都有兩個字段: field1
和field2
。 僅當請求字段的主對象不是從屬對象的所有者時,才需要從主對象訪問字段。
class SlaveObj()
{
...
private readonly int field1;
private readonly string field2;
...
public int GetField1()
{
// if asker object is not my owner
// return field1
}
}
class MainObj()
{
...
List<SlaveObj> slaves = new List<SlaveObj>();
...
public int GetField1(MainObj other)
{
return other.slaves[0].GetField1();
}
}
首先,我嘗試過的是這個 。 就像在第一個答案中一樣,我只是嘗試檢查哪個對象是詢問者。 但是對於MainObj的任何實例,我都有類似Project1.MainObj
的東西。 因此,我無法識別請求者是否是所有者。
更改后的代碼(不適用於我想要的)
class SlaveObj()
{
...
private MainObj owner;
private readonly int field1;
private readonly string field2;
...
public int GetField1(MainObj asker)
{
if(asker != owner) return field1;
}
}
class MainObj()
{
...
List<SlaveObj> slaves = new List<SlaveObj>();
...
public int GetField1(MainObj other)
{
return other.slaves[0].GetField1(this);
}
}
我的朋友,這應該可以解決您需要的方式。 但是您必須將ID添加到父對象。
internal class SlaveObj
{
private MainObj owner;
private readonly int field1;
private readonly string field2;
public SlaveObj(MainObj parent)
{
this.owner = parent;
}
public int GetFieldID(int askerID)
{
if (askerID != owner.ID) return field1;
return 0;
}
}
class MainObj
{
public int ID;
List<SlaveObj> slaves = new List<SlaveObj>();
public int GetFieldID(MainObj other)
{
return other.slaves[0].GetFieldID(this.ID);
}
public MainObj(int id)
{
this.ID = id;
}
}
您的先前版本無法正常運行,因為您的主要對象是引用類型,默認情況下會通過引用對其進行比較。 因此,最好使用對象ID在MainObj中實現IEqualtyComparer:
class MainObj : IEqualityComparer
容易修復
class SlaveObj()
{
MainObj _owner;
readonly int _field1 = ...;
readonly string _field2 = ...;
// you need a way to set owner, e.g. constructor parameter
public SlaveObj(MainObj owner)
{
_owner = owner; // good example why underscore in field name is good
}
// return type: object
// renamed
// using C# 6.0 features to confuse people
public object GetFieldX(MainObj asker) => asker != _owner ? _field1 : _field2;
}
class MainObj()
{
List<SlaveObj> _slaves = new List<SlaveObj>();
// return first slave field value
// has nothing to do with instance, therefore static
// will return null if no slave
public static object GetFieldX(MainObj owner) => owner?.FirstOrDefault()?.GetFieldX(this);
}
但這不漂亮。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.