are there function pointers in c#?

前端 未结 6 1283
后悔当初
后悔当初 2020-12-07 01:40

I am trying to learn some c# coding and wondering if the c++ concept of function pointers is included in c#. I see there are such things as delegates. Are they the same co

6条回答
  •  难免孤独
    2020-12-07 02:20

    C# does have something like a function pointer, which is call delegate. Well... I can't really give you a theoretical answer to the difference between them. But I can give you a difference in code implementation between C# delegate vs C++ function pointers.

    C#

    delegate void voidFn();
    voidFn fnDel;
    List intList = new List();
    fnDel = intList.Clear
    

    This would compile in c# easily.

    C++

    typedef void (*voidFn)();
    voidFn fnDel;
    std::vector intList;
    fnDel = intList.clear;
    

    Nope... I am sorry to tell you that in c++ this will not work, even though logically speaking, it felt like the vector's clear function is the same as a void fn(). We don't simply point to an address of the vector's function and say, "Hey! let's clear this vector at this callback" I hope someone can reply a more concrete explanation to this, but I am guessing it got something to do with not knowing which vector to look for.

    However, with a little bit of polymorphism... we can transfer something like a C# delegate around...

    #include 
    #include 
    
    class A
    {
    public:
        A() {}
        virtual void operator()() { std::cout << "A is called"; }
    };
    
    class B : A
    {
    public:
        B(std::vector& vec):vec_(vec){}
        void operator()() { vec_.clear(); std::cout << "B is called" << std::endl; }
    
    private:
        std::vector& vec_;
    };
    
    int main() 
    {
        std::vector tmpVec;
        for (int i = 0; i < 10; ++i)
        {
            tmpVec.push_back(i);
        }
        B* b = new B(tmpVec);
        A* a = (A*)b;
    
        std::cout << "Current vec size: " << tmpVec.size() << std::endl;
    
        (*a)();
    
        std::cout << "Current vec size: " << tmpVec.size() << std::endl;
    
        delete b;
    
        return 0;
    }
    

    Yup.. that's right... with the help of functors and a little inheritance with their virtual function thingy, we can actually have a form of "delegate void VoidFn()" in Class A. The above code would run class B because of how inheritance work, and will clear 'tmpVec' for us.. So YIPPEE, we can write a pretty flexible C++ callback that doesn't rely on a 'unflexible' function pointer after all!

提交回复
热议问题