Build a static delegate from non-static method

后端 未结 5 1150
无人共我
无人共我 2021-01-06 08:28

I need to create a delegate to a non-static method of a class. The complications is that at the time of creation I don\'t have an intance to the class, only its class defini

5条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-06 09:03

    What's wrong with just passing an instance in like this?

    // Creation.
    Action bar = foo =>
    {
        foo.Baz();
    };
    
    // Invocation.
    bar(new Foo());
    

    It does all you need it to: it encapsulates the logic you want to pass around, and can be invoked on an arbitrary class instance.

    Edit: If you're restricted to using a delegate of a certain signature (not allowing an instance to be passed explicitly as a parameter), then you could use some form of "instance provider" which is specified at the time of the delegate's creation, but can be mutated later to provide the appropriate instance when it becomes available, e.g.:

    class Provider
    {
        public T Instance { get; set; }
    }
    
    static Action Create(Provider provider)
    {
        return () =>
        {
            provider.Instance.Baz();
        };
    }
    
    // ...
    
    // Creation.
    var provider = new Provider();
    var bar = Create(provider);
    
    // Invocation.
    provider.Instance = new Foo();
    bar();
    

    Of course, this is a bit convoluted, and requires an additional object to be passed around, so perhaps it's not ideal!

提交回复
热议问题