2

我有不可变的 F1 类。我想改变它的一个领域。在 set 方法中,我必须返回 F1 类的新实例并进行更改。我不明白我怎么能做到这一点。

public class F1
{
    public readonly int k1;
    public readonly ImmutableList<int> k2;

    public F1(int k)
    {
        ...
    }

    public int GetItem(int pos)
    {
        return k2[pos];
    }

    public F1 SetItem(int pos, int val)
    {
        return new F1() // How i can create new instance with changes in pos
    }
}

String.cs 中有 Replace 方法。String 是 C# 中的不可变类(或者我认为是这样)。替换方法定义如下:

[SecuritySafeCritical]
[MethodImpl(MethodImplOptions.InternalCall)]
private string ReplaceInternal(char oldChar, char newChar);

[__DynamicallyInvokable]
public string Replace(char oldChar, char newChar)
{
  return this.ReplaceInternal(oldChar, newChar);
}

所以我不知道 ReplaceInternal 是如何工作的,然后找不到我的问题的答案。

4

3 回答 3

1

很难说出您在构造函数中到底要做什么,但您可以添加另一个接受 ImmutableList 的构造函数,如 Kryzsztof 所示并修改 SetItem 方法,如下所示:

public F1 SetItem(int pos, int val)
{
    return new F1(k1, k2.SetItem(pos, val));
}

全面实施:

public class F1
{
    public readonly int k1;
    public readonly ImmutableList<int> k2;

    public F1(int k)
    {
        ...
    }

    private F1(int k1, ImmutableList<int> k2)
    {
        this.k1 = k1;
        this.k2 = k2;
    }

    public int GetItem(int pos)
    {
        return k2[pos];
    }

    public F1 SetItem(int pos, int val)
    {
        return new F1(k1, k2.SetItem(pos, val));
    }
}

请注意,我将新构造函数设为私有,假设您不想将此构造函数公开用于此目的以外的任何用途。

编辑:我还应该注意 ImmutableList 的语义是这样的,即使用典型列表方法对列表进行的任何修改都会产生一个新列表,例如对 SetItem 的调用:

k2.SetItem(pos, val)
于 2015-09-26T17:24:30.120 回答
0

假设您有如下构造函数:

public F1(int k1, ImmutableList<int> k2)
{
    this.k1 = k1;
    this.k2 = k2;
}

您可以通过创建和返回具有更改属性的新对象而不是改变当前对象来创建修改属性的方法。

public F1 SetK1(int newk1)
{
    return new F1(newk1, this.k2);
}

public F1 SetK2(ImmutableList<int> newK2)
{
    return new F1(this.k1, newK2);
}
于 2015-09-26T16:54:36.710 回答
0

您的解决方案基于 String 的Replace方法,这可能不是最好的主意。StackOverflow 的历史表明,人们,尤其是 .NET 框架的新手,经常会误解 .NET 的语义String.Replace,因为它的语法并不意味着不变性,而且你不得不依赖外部文档或先验知识。

我不会创建实际上不设置值的 setter/Set 方法,而是创建一个名为“GetModifiedCopy”的方法,该方法显式返回带有修改后的值的新副本。这个

public class F1
{
    public readonly int k1;

    public F1(int k1)
    {
      ...
    }

    public F1 GetModifiedCopy(int newVal)
    {
        return new F1(newVal);
    }
}

现在,您的情况有点复杂,因为您不仅要使用单个值实例化一个新实例,而且要复制整个现有列表并修改一个值。不过解决方法是一样的——创建一个私有构造函数,接收原始列表和新值,在构造函数中修改列表,返回新实例。

private F1(ImmutableList<int> baseList, int pos, int value)
{
    var tempList = baseList.ToList(); // create mutable list.
    tempList[pos] = value; // modify list.
    this.k2 = new ImmutableList<int>(tempList); // immutablize!
}
public F1 GetModifiedCopy(int pos, int value)
{
    return new F1(this.k2, pos, value);
}
于 2015-09-26T17:22:19.377 回答