为什么要获得Action<>的克隆版本从字典中获得什么? [英] Why do I get a clone of Action<> when getting from dictionary?

查看:65
本文介绍了为什么要获得Action<>的克隆版本从字典中获得什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下字典:

private Dictionary<string, Action<GameObject, int, int, int, int>> eventDictionary;

我希望保留一个行动字典"(基本上是代表),以便每当我希望订阅事件名称时,便可以为我的所有订阅者订阅同一事件.

I wish to keep a dictionary of Actions (basically delegates) so that whenever I wish to subscribe to an event name, I can subscribe to the same event for all my subscribers.

这是我侦听特定事件字符串的功能:

This is my function to listen to a certain event string:

public static void StartListening(string eventName, Action<GameObject, int, int, int, int> listener)
{
    Action<GameObject, int, int, int, int> thisEvent = null;
    if (instance.eventDictionary.TryGetValue(eventName, out thisEvent))
    {
        thisEvent += listener;
        // the code reaches this 
    }
    else
    {
        thisEvent += listener;
        instance.eventDictionary.Add(eventName, thisEvent);
    }
}

现在我尝试

EventManager.StartListening("Move", Moved);
EventManager.StartListening("Move", Moved);
EventManager.StartListening("Move", Moved);
EventManager.StartListening("Move", Moved);

// Log here to get how many subscribers there are to the event "Move"
// Result: only 1 listener

只有第一个添加的侦听器将实际注册,其余的添加后将消失".我调试了此错误将近4个小时,然后才进行最终测试以查看thisEvent += listener;行是否出现故障.当我添加删除并随后将其添加回字典时,

Only the first added listener will actually register, the rest "disappear" after adding them. I debugged this error for nearly 4 hours, before finally testing to see if maybe the line thisEvent += listener; was malfunctioning. When I added a remove and subsequent add back to the dictionary,

public static void StartListening(string eventName, Action<GameObject, int, int, int, int> listener)
{
    Action<GameObject, int, int, int, int> thisEvent = null;
    if (instance.eventDictionary.TryGetValue(eventName, out thisEvent))
    {
        thisEvent += listener;
        instance.eventDictionary.Remove(eventName);
        instance.eventDictionary.Add(eventName, thisEvent);
    }
    else
    {
        thisEvent += listener;
        instance.eventDictionary.Add(eventName, thisEvent);
    }
}

代表们终于按预期加入了.

the delegates finally got added as expected.

EventManager.StartListening("Move", Moved);
EventManager.StartListening("Move", Moved);
EventManager.StartListening("Move", Moved);
EventManager.StartListening("Move", Moved);

// Log here to get how many subscribers there are to the event "Move"
// Result: 4 listeners

这是我所遇到的最荒谬的错误之一.难道不是字典中不是字符串,整数等所有值都应该通过引用而不是值来检索吗?为什么我在这里获得Action的克隆,而不是参考?

This is one of the most nonsensical errors I have ever gotten. Aren't all values in a dictionary that aren't strings, ints, etc. supposed to be retrieved by reference, not by value? Why do I get a clone of the Action here, rather than a reference?

PS: GameObject是Unity类. 这是我的Moved函数:

PS: GameObject is a Unity class. This is my Moved function:

public void Moved(GameObject invoker, int x, int z, int tx, int tz)
{
    //Some code here
}

推荐答案

这是我遇到过的最荒谬的错误之一.难道不是字典中不是字符串,整数等所有值都应该通过引用而不是值来检索吗?为什么我在这里获得Action的克隆,而不是参考?

This is one of the most nonsensical errors I have ever gotten. Aren't all values in a dictionary that aren't strings, ints, etc. supposed to be retrieved by reference, not by value? Why do I get a clone of the Action here, rather than a reference?

当您调用TryGetValue(eventName, out thisEvent)时,您将提供一个引用,Dictionary将在该引用中写入该值.您没有获得对Dictionary内部内容的引用(我的意思是,您没有得到对Dictionary结构的深入了解,这意味着分配给它不会修改Dictionary).

When you call TryGetValue(eventName, out thisEvent) you are providing a reference to which the Dictionary will write the value. You are not getting a reference to what is inside the Dictionary (I mean, you are not getting a deep pointer to the Dictionary structure, meaning that assigning to it will NOT modify the Dictionary).

也许委托可能是一个引用类型,这可能会引起一些混淆. 是的,您得到的是对同一委托对象的引用,而不是对新委托的引用.但是,委托添加会返回一个新的多播委托.

Perhaps some confusion might stem from the fact that a delegate is a reference type. And yes, you get a reference to the same delegate object, not a new one. However, delegate addition returns a new multicast delegate.

顺便说一句,string是引用类型.

By the way, string is a reference type.

请参阅:

  • How to combine delegates (Multicast Delegates) (C# Programming Guide)
  • How does the + operator work for combining delegates?.

我只是想知道为什么要这样设计.几乎所有语言都有字典,可在获取对象时为您提供参考.当我不确定它是否为null时,还应该如何获取对象?

I'm just left wondering why it is designed that way. Almost all languages have dictionaries that give you back a reference when getting objects. How else should I get objects when I am not sure if it is null?

内存安全.这种设计将不可能有孤立的指针或类似的指针.

Memory safety. There will be no chance of orphan pointers or similar with this design.

尽管如此,如果没有替代的更新API,也可以视为一种疏忽,例如

Although, it can be considered an oversight not to have an alternative API for updates, such as ConcurrentDictionary<TKey,TValue>.AddOrUpdate. Dictionary is not meant to be thread safe, and you can accomplish the same thing, even if less efficiently... that would explain why it was not considered necesary.

如果您正在寻找替代方法(ConcurrentDictionary除外),则可以使用可变引用类型.例如List<Delegate>.在TryGetValue(eventName, out thisEvent)中,您仍将提供编写List<Delegate>的参考,但是,您可以对其进行突变.但是,您仍然需要处理初始化,如果不存在密钥,您将需要执行初始化. 您不会有空值.

If you are looking for an alternative (other than ConcurrentDictionary) you can use a mutable reference type. Such as List<Delegate> for example. In TryGetValue(eventName, out thisEvent) you would still be providing a reference to which to write the List<Delegate>, however, you can then mutate it. However, you still have to deal with initializing it, which you would do when the key is not present. You would not have nulls.

if (instance.eventDictionary.TryGetValue(eventName, out var thisEvent))
{
    thisEvent.Add(listener);
}
else
{
    instance.eventDictionary.Add
    (
        eventName,
        new List<Action<GameObject, int, int, int, int> {listener}
    );
}


这也让我感到奇怪,它是深克隆还是浅克隆?

This also makes me wonder, is it a deep or shallow clone?

如果要存储值类型,则将获得该值类型的副本.

If you are storing a value type, you get a copy of the value type.

如果要存储引用类型,则将获得引用的副本.我不会称其为克隆.它只是对同一对象的另一种引用.

If you are storing a reference type, you get copy of the reference. I would not call that cloning. It is just another reference to the same object.

这篇关于为什么要获得Action&lt;&gt;的克隆版本从字典中获得什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆