为什么在C#中通过引用添加字典元素?

时间:2016-05-15 14:47:43

标签: c# dictionary key fakeiteasy

我正在尝试做一些似乎应该很容易的事情,但它无法正常工作。我有一个带有int键的字典对象。在对象中,我有一个属性PositionInEvent,我想要匹配其中字典的键。看起来这应该是一个简单的循环操作,但它不起作用。这就是我所拥有的:

private void ensurePositions(ref Dictionary<int, DisplayUnit>  dict)
{
    var keys = dict.Keys.ToArray();
    foreach(var key in keys)
    {
        dict[key].PositionInEvent = key;
    }
}

当我在一个包含0-4键的5个对象的字典上运行它时(它不会像这样顺序,但我是单元测试它),事件中每个项目的PositionInEvent属性都有一个价值4.每一个。为什么????我怎么能做我想做的事。看起来应该很简单。

更新

要求我展示如何声明,实例化DisplayUnit并将其添加到字典中。

这是类声明(我已经取出了与实例化无关的东西以及我在这里使用的属性):

/// <summary>
/// This is the base display unit from which all other units are derived.
/// </summary>
public abstract class DisplayUnit
{

    /// <summary>
    /// Initializes a new instance of the <see cref="AbstractClasses.DisplayUnit"/> class.
    /// </summary>
    protected DisplayUnit (Dictionary<string,string> attributes)
    {
        this.Id = Guid.NewGuid();
        tryApplyAttributes(attributes);
    }

    protected DisplayUnit(Guid id, Dictionary<string,string> attributes)
    {
        this.Id = id;
        tryApplyAttributes(attributes);
    }

    private void tryApplyAttributes(Dictionary<string,string> attributes)
    {
        string name;
        attributes.TryGetValue("Name", out name);
        Name = name;

        string description;
        attributes.TryGetValue("Description", out description);
        Description = description;

        string dateTime;
        attributes.TryGetValue ("DateCreated", out dateTime);
        DateTime date;
        DateTime.TryParse(dateTime,out date);
        DateCreated = date;

        string guid;
        attributes.TryGetValue("AssociatedEvent", out guid);
        Guid id;
        Guid.TryParse(guid, out id);
        AssociatedEvent = id;

        string group;
        attributes.TryGetValue("GroupId", out group);
        Guid groupId;
        var groupSet = Guid.TryParse(group, out groupId);

        string posInGroup;
        attributes.TryGetValue("PositionInGroup", out posInGroup);
        int intPos;
        var posSet = int.TryParse(posInGroup, out intPos);

        if (posSet && groupSet)
            UnitGroup = new DisplayUnitGrouping (intPos, groupId);

        string pos;
        attributes.TryGetValue("PositionInEvent", out pos);
        int position;
        int.TryParse (pos, out position);
        PositionInEvent = position;
    }

    public Guid Id {
        get;
        private set;
    }

    private int _positionInEvent;
    public int PositionInEvent {
        get{
            return _positionInEvent;
        }
        set {
            if (value < 0) {
                throw new NegativePositionException ("Position of DisplayUnit must be positive.");
            }
            _positionInEvent = value;
        }
    }

}

TextUnit是我实际使用的类,它派生自DisplayUnit:

public class TextUnit : DisplayUnit
{
    public string Text {
        get;
        set;
    }

    public TextUnit (Dictionary<string, string> attributes) : base (attributes)
    {
        SetAttributes (attributes);
        Plugin = new FaithEngage.Plugins.DisplayUnits.TextUnitPlugin.TextUnitPlugin ();
    }


    public TextUnit (Guid id, Dictionary<string, string> attributes) : base (id, attributes)
    {
        SetAttributes (attributes);
    }


    #region implemented abstract members of DisplayUnit

    public override void SetAttributes (Dictionary<string, string> attributes)
    {
        string text;
        attributes.TryGetValue ("text", out text);
        Text = text;
    }

    #endregion
}

正在采取行动的字典来自这里。 _duRepo是一个伪造的存储库(请参阅下面的代码)。

public Dictionary<int, DisplayUnit> GetByEvent(Guid eventId)
{
    try {
        var returnDict = new Dictionary<int,DisplayUnit>();
        var dict = _duRepo.GetByEvent(eventId);
     if (dict == null)
            return null;
        foreach(var key in dict.Keys)
        {
            var du = _factory.ConvertFromDto(dict [key]);
            if(du == null) continue;
            returnDict.Add (key, du);
        }
        ensurePositions(ref returnDict);
        return returnDict;
    } catch (RepositoryException ex) {
        throw new RepositoryException ("There was a problem accessing the DisplayUnitRepository", ex);
    }
 }

这一切都来自这个单元测试(我无法通过,我不知道为什么):

[Test]
public void GetByEvent_ValidEventId_ReturnsDictOfEvents()
{
    var dict = new Dictionary<int,DisplayUnitDTO>();
    for(var i = 0; i < 5; i++)
    {
        dict.Add(i, new DisplayUnitDTO());
    }
    var repo = A.Fake<IDisplayUnitsRepository>();
    A.CallTo(() => repo.GetByEvent(VALID_GUID)).Returns(dict);
    A.CallTo(() => _fctry.ConvertFromDto(null))
        .WithAnyArguments()
        .Returns(
            new TextUnit(
                new Dictionary<string,string>(){
                    { "Text", "This is my Text" }
                }
            )
        );
    A.CallTo (() => _container.Resolve<IDisplayUnitsRepository>()).Returns(repo);
    var mgr = new DisplayUnitsRepoManager(_container);
    var duDict = mgr.GetByEvent(VALID_GUID);
    Assert.That(duDict, Is.InstanceOf(typeof(Dictionary<int,DisplayUnit>)));
    Assert.That(duDict, Is.Not.Null);
    Assert.That(duDict.Count == 5);
    foreach(var key in duDict.Keys)
    {
        Assert.That(duDict[key].PositionInEvent == key);
    }
}

1 个答案:

答案 0 :(得分:2)

所以评论在这里很有启发性。基于这些,我意识到了我需要看的方向。罪魁祸首就是这条线:

 A.CallTo(() => _fctry.ConvertFromDto(null))
    .WithAnyArguments()
    .Returns(
        new TextUnit(
            new Dictionary<string,string>(){
                { "Text", "This is my Text" }
            }
        )
    );

基本上,这与FakeItEasy及其伪造返回值的方式有关。即使我在返回值中创建了一个TextUnit,FakeItEasy也会在调用_fctry.ConvertFromDto()时单独返回对该对象的引用。因此,我的假装给了我奇怪的行为,否则不会发生(我不会通过引用多次将相同的项目添加到字典中)。

无论如何,我能够通过改变我的返回规范来解决这个问题:

A.CallTo (() => _fctry.ConvertFromDto (null))
    .WithAnyArguments()
    .ReturnsLazily((DisplayUnitDTO d) => new TextUnit(d.Attributes));

在我测试完之后,每次调用函数时都会创建一个新的文本单元。 (顺便说一句......我知道我实际上并没有在lambda中使用d,但是我需要使用与调用相同的签名伪造返回值。)

感谢评论者及其指点。我已将此问题重命名为更好地与实际发生的事情相关联。

相关问题