Cast delegate to Func in C#

后端 未结 8 2044
小蘑菇
小蘑菇 2020-12-01 12:03

I have code:

public delegate int SomeDelegate(int p);

public static int Inc(int p) {
    return p + 1;
}

I can cast Inc to

相关标签:
8条回答
  • 2020-12-01 12:29

    The problem is that:

    SomeDelegate a = Inc;
    

    Isn't actually a cast. It's the short-form of:

    SomeDelegate a = new SomeDelegate(Inc);
    

    Therefore there's no cast. A simple solution to your problem can be this (in C# 3.0)

    Func<int,int> f = i=>a(i);
    
    0 讨论(0)
  • 2020-12-01 12:29

    You can hack a cast by using a trick where you use the c# equivalent of a c++ union. The tricky part is the struct with two members that have a [FieldOffset(0)]:

    [TestFixture]
    public class Demo
    {
        public void print(int i)
        {
            Console.WriteLine("Int: "+i);
        }
    
        private delegate void mydelegate(int i);
    
        [StructLayout(LayoutKind.Explicit)]
        struct funky
        {
            [FieldOffset(0)]
            public mydelegate a;
            [FieldOffset(0)]
            public System.Action<int> b;
        }
    
        [Test]
        public void delegatetest()
        {
            System.Action<int> f = print;
            funky myfunky;
            myfunky.a = null;
            myfunky.b = f;
    
            mydelegate a = myfunky.a;
    
            a(5);
        }
    }
    
    0 讨论(0)
提交回复
热议问题