在 C# 中将委托强制转换为 Func

问题描述 投票:0回答:8

我有一些代码:

public delegate int SomeDelegate(int p);

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

我可以将

Inc
投射到
SomeDelegate
Func<int, int>
:

SomeDelegate a = Inc;
Func<int, int> b = Inc;

但我不能像这样将

SomeDelegate
投射到
Func<int, int>

Func<int, int> c = (Func<int, int>)a; // Сompilation error

我该怎么做?

c# .net casting delegates
8个回答
84
投票

有一种更简单的方法来做到这一点,所有其他答案都忽略了:

Func<int, int> c = a.Invoke; 

请参阅此博文了解更多信息。


58
投票
SomeDelegate a = Inc;
Func<int, int> b = Inc;

的缩写
SomeDelegate a = new SomeDelegate(Inc); // no cast here
Func<int, int> b = new Func<int, int>(Inc);

您无法将 SomeDelegate 的实例强制转换为 Func,其原因与您无法将字符串强制转换为 Dictionary 的原因相同——它们是不同的类型。

这有效:

Func<int, int> c = x => a(x);

这是

的语法糖
class MyLambda
{
   SomeDelegate a;
   public MyLambda(SomeDelegate a) { this.a = a; }
   public int Invoke(int x) { return this.a(x); }
}

Func<int, int> c = new Func<int, int>(new MyLambda(a).Invoke);

31
投票

试试这个:

Func<int, int> c = (Func<int, int>)Delegate.CreateDelegate(typeof(Func<int, int>), 
                                                           b.Target,
                                                           b.Method);

9
投票

问题在于:

SomeDelegate a = Inc;

实际上不是演员。它的缩写形式是:

SomeDelegate a = new SomeDelegate(Inc);

因此没有演员阵容。您的问题的一个简单解决方案可以是这样(在 C# 3.0 中)

Func<int,int> f = i=>a(i);

8
投票

这有效(至少在 C# 4.0 中 - 没有在早期版本中尝试过):

SomeDelegate a = Inc;
Func<int, int> c = new Func<int, int>(a);

如果你查看 IL,它会编译成与 Winston 的答案完全相同的代码。这是我刚刚写的第二行的 IL:

ldloc.0
ldftn      instance int32 ConsoleApplication1.Program/SomeDelegate::Invoke(int32)
newobj     instance void class [mscorlib]System.Func`2<int32,int32>::.ctor(object, native int)

如果您将

a.Invoke
分配给
c
,这也正是您所看到的。

顺便说一句,虽然迭戈的解决方案更有效,因为生成的委托直接引用底层方法而不是通过其他委托,但它不能正确处理多播委托。温斯顿的解决方案确实如此,因为它完全服从于另一个代表。如果您想要一个可以处理具有多个目标的委托的直接解决方案,则需要更复杂的东西:

public static TResult DuplicateDelegateAs<TResult>(MulticastDelegate source)
{
    Delegate result = null;
    foreach (Delegate sourceItem in source.GetInvocationList())
    {
        var copy = Delegate.CreateDelegate(
            typeof(TResult), sourceItem.Target, sourceItem.Method);
        result = Delegate.Combine(result, copy);
    }

    return (TResult) (object) result;
}

顺便说一句,这对于具有单个目标的委托来说是正确的——它最终只会生成一个目标类型的委托,该委托直接引用输入委托所引用的任何方法(以及适用的对象)。


6
投票

您可以通过使用相当于 C++ 联合的 C# 技巧来破解强制转换。棘手的部分是具有两个具有 [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);
    }
}

4
投票

与此是同一类问题:

public delegate int SomeDelegate1(int p);
public delegate int SomeDelegate2(int p);
...
  SomeDelegate1 a = new SomeDelegate1(Inc);
  SomeDelegate2 b = (SomeDelegate2)a;  // CS0030

这是同一类问题:

public class A { int prop { get; set; } }
public class B { int prop { get; set; } }
...
  A obja = new A();
  B objb = (B)obja;  // CS0029

对象不能从一种类型转换为不相关的其他类型,即使这些类型在其他方面完全兼容。 由于缺乏更好的术语:对象具有在运行时携带的类型标识。 创建对象后,该身份无法更改。 这个身份的可见表现是Object.GetType()。


1
投票

我喜欢例子。这是我的示例代码:

class Program
{
    class A
    {
        public A(D d) { d.Invoke("I'm A!"); }
        public delegate string D(string s);
    }

    class B
    {
        public delegate string D(string s);
    }
    static void Main(string[] args)
    {
        //1. Func to delegates 

        string F(dynamic s) { Console.WriteLine(s); return s; }
        Func<string, string> f = F;
        //new A(f);//Error CS1503  Argument 1: cannot convert from 'System.Func<string, string>' to 'ConsoleApp3.Program.A.D'  
        new A(new A.D(f));//I'm A!
        new A(x=>f(x));//I'm A!

        Func<string, string> f2 = s => { Console.WriteLine(s); return s; };
        //new A(f2);//Same as A(f)
        new A(new A.D(f2));//I'm A!
        new A(x => f2(x));//I'm A!

        //You can even convert between delegate types
        new A(new A.D(new B.D(f)));//I'm A!



        //2. delegate to F

        A.D d = s => { Console.WriteLine(s); return s; };

        Func<string, string> f3 = d.Invoke;
        f3("I'm f3!");//I'm f3!
        Func<string, string> f4 = new Func<string, string>(d);
        f4("I'm f4!");//I'm f4!


        Console.ReadLine();
    }
}

输出为:

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.