gpt4 book ai didi

c# - System.Action 内部是一个数组吗? += 和 -= 运算符的效率

转载 作者:行者123 更新时间:2023-11-30 17:25:14 25 4
gpt4 key购买 nike

我需要不断地向委托(delegate)添加和删除操作,我应该使用哈希集而不是操作吗?

我目前拥有的:

System.Action _callbacks =null;

//...somewhere in code, from many different places (2000 places or so, every frame):
_callbacks -= anyFunction;
_callbacks += someOtherFunc;

我可能会使用什么(基本上是回调的哈希集):

Hashset<FastFunc> _callbacks = new Hashset<FastFunc>();


//...somewhere in code, from many different places
_callbacks.add( new FastFunc(someOtherFunc) );

// works A LOT faster with hashsets that System.Action does. //(March2019 profiler)
// It remembers its hashcode once, then can provide it super-quickly every time it's required.
public class FastFunc{
public System.Action _func;
private int _hashCode;

public FastFunc(System.Action function){
_func = function;
remember_HashCode(function);
}

public override int GetHashCode(){
return _hashCode;
}

// important to override Equals as well, so that objects created from the same method
// will be identical.
public override bool Equals(object other){
System.Action otherAction = ((FastFunc)other)._func;

bool isEqual = otherAction.Method.Equals( _func.Method ) && otherAction.Target.Equals( _func.Target );
return isEqual;
}

//only called once, during constructor
void remember_HashCode(System.Action myFunc){
_hashCode = myFunc.GetHashCode();
}
}

使用这个 -= 和 += 运算符是否可以订阅 System.Action

它是否在幕后使用了一个数组,如果我们从它的起始索引中删除一些函数,它就必须被移回?如果是这样,我想 hashset 会是更好的选择 + 没有重复项。

最佳答案

多播委托(delegate)的调用列表数组。

https://referencesource.microsoft.com/#mscorlib/system/multicastdelegate.cs,284

(文档已过时(代表们可能在 .Net 1.0 中使用过 linked-linsts,但不再使用)https://learn.microsoft.com/en-us/dotnet/api/system.multicastdelegate?view=netframework-4.8 )

您可以使用您的方法使添加/删除操作更快。事实上,AFAIR,WPF 就是这样做的。

不过你需要小心多线程。

关于c# - System.Action 内部是一个数组吗? += 和 -= 运算符的效率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58922311/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com