在C#中对类型的每个实例调用方法 [英] Calling a method on every instance of a type in c#

查看:45
本文介绍了在C#中对类型的每个实例调用方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道您可以调用为每个对象执行的实例方法.我也知道您可以在可从类型调用的类型上使用静态方法.

I know that you can call an instance method that executes for each object. I also know that you can have a static method on the type that is callable from the type.

但是如何调用一种对特定类型的每个实例起作用的方法(例如,将成员变量设置为零)?

But how would one call a method that acts on every instance of a particular type (say, to set a member variable to zero, for example)?

推荐答案

C#没有提供直接的机制来跟踪所有可到达的对象,因此几乎没有充分的理由想要这种自动跟踪功能(而不是说由您自己管理的显式池).

C# doesn't provide a direct mechanism to track all reachable objects and there's almost never a good reason to want such automatic tracking functionality (rather than, say, an explicit pool that you manage yourself).

但是要直接回答您的要求,您需要:

But to answer your requirement directly, you'll need to:

  1. 手动跟踪该类型的所有可达实例(也许使用一组弱引用,以防止跟踪器本身延长对象的寿命).
  2. 提供一种机制(例如对这个集合的每个成员执行副作用).
  3. 销毁对象时,请从集中摆脱关联的弱引用.这对于防止弱参考泄漏是必要的.

所有这些都必须以线程安全的方式完成.

All of this will have to be done in a thread-safe manner.

public class Foo
{
    private static readonly HashSet<WeakReference> _trackedFoos = new HashSet<WeakReference>();
    private static readonly object _foosLocker = new object();

    private readonly WeakReference _weakReferenceToThis;

    public static void DoForAllFoos(Action<Foo> action)
    {
        if (action == null)
            throw new ArgumentNullException("action");

        lock (_foosLocker)
        {
            foreach (var foo in _trackedFoos.Select(w => w.Target).OfType<Foo>())
                action(foo);
        }
    }

    public Foo()
    {
       _weakReferenceToThis = new WeakReference(this);

        lock (_foosLocker)
        {
            _trackedFoos.Add(_weakReferenceToThis);
        }
    }

    ~Foo()
    {
        lock (_foosLocker)
        {
            _trackedFoos.Remove(_weakReferenceToThis);
        }
    }
}

您确定需要所有这些吗?这真的很奇怪,而且不确定(将在发生垃圾收集时受到严重影响).

Are you sure you need all of this though? This is all really strange and non-deterministic (will be heavily impacted by when garbage-collection occurs).

这篇关于在C#中对类型的每个实例调用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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