![](/img/trans.png)
[英]How can I create a class whose object takes a function in the constructor and can execute it?
[英]How can I create a method whose argument is a function whose argument can be an object from any class extending a given class?
我有从A
继承的类B
和C
。
public class A { }
public class B : A { }
public class C : A { }
我有一些将对象B
和C
作为参数的函数:
public void FunB(B obj) { }
public void FunC(C obj) { }
我想创建一个接受任何这些函数作为参数的函数。 我尝试使用委托,但找不到解决方案。 我试过这个,但我收到以下错误:
public class Test
{
public void FunB(B obj) { }
public void FunC(C obj) { }
public delegate void Delegate(A obj);
public static void Method(Delegate fun) { }
public void Pain()
{
Delegate funB = FunB; // No overload for FunB matches the delegate Test.Delegate
Delegate fun2 = (A obj) => { };
fun2 += FunB; // No overload for FunB matches the delegate Test.Delegate
Method(FunB); // Argument 1: cannot convert from 'method group' to 'Test.Delegate'
}
}
我阅读了文档(这就是我尝试使用fun2 += FunB
)但很明显有些我不明白。 知道如何修复它吗?
您可以编写这样的方法来将Action<B>
调整为Action<A>
(现在您通常应该更喜欢使用这些通用委托):
public Action<TA> ActWithParent<TA, TB> (Action<TB> original) where TB: TA
{
return a =>
{
if(a is TB b)
{
original(b);
}
};
}
public void Pain()
{
Action<A> fun2 = ActWithParent<A, B>(FunB);
fun2 += ActWithParent<A,C>(FunC);
}
它可能有一个更好的名称,但请注意,它仅在实际获得匹配类型时才调用“子”方法,这是您需要在此处在调用方和被调用方之间插入的额外检查。 另请注意,如果没有类型匹配,您可能希望指定不同的行为。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.