C#不常访问对象的属性

时间:2016-02-01 15:36:24

标签: c# oop properties

我有几个主对象。每个人都有奴隶对象列表。每个从属对象都有两个字段:field1field2。只有当请求该字段的主对象不是从属对象的所有者时,我才需要访问主对象中的字段。

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();
    }
}

首先,我尝试过的是this。我只是试着像第一个答案一样检查提问者的对象。但对于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);
    }
}

2 个答案:

答案 0 :(得分:1)

我的朋友,这应该按照你需要的方式解决。但是你必须在父对象中添加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

答案 1 :(得分:0)

很容易修复

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);
}

但它并不漂亮。