如何将操作转换为具有相同签名的已定义委托?
class Test
{
public delegate void FruitDelegate(Fruit f);
public void Notify<T>(Action<T> del) where T : Fruit
{
FruitDelegate f = del; // Cannot implicitly convert type 'Action<T>' to 'FruitDelegate
}
}
水果是一个空类。这两位代表都有相同的签名。
我似乎无法让这些工作发挥作用。如果我解释一下我想要做什么(提供一些背景信息),也许会有帮助。
我想创建一个具有通用静态方法的类,该方法提供类型和方法回调(如上面的示例)。
我遇到的问题是委托包含一个参数,我不想在方法回调中强制转换它。例如,我想要这个:
public void SomeMethod()
{
Test.Notify<Apple>(AppleHandler);
}
private void AppleHandler(Apple apple)
{
}
而不是这个:
public void SomeMethod()
{
Test.Notify<Apple>(AppleHandler);
}
private void AppleHandler(Fruit fruit)
{
Apple apple = (Apple)fruit;
}
这种事情可能吗?
class Test
{
public delegate void FruitDelegate(Fruit f);
public void Notify<T>(Action<T> del) where T : Fruit
{
FruitDelegate f = del; // Cannot implicitly convert type 'Action<T>' to 'FruitDelegate
}
}
Fruit is an empty class. Both of these delegates have the same signature.
I cannot seem to get any of this working. Maybe it would help if I explained what I am trying to do (provide some context).
I want to create a class that has a generic static method that provides a type and a method callback (like the above example).
The problem I am having is that the delegate contains a parameter and I don't want to have to cast it within the method callback. For example, I want this:
public void SomeMethod()
{
Test.Notify<Apple>(AppleHandler);
}
private void AppleHandler(Apple apple)
{
}
Instead of this:
public void SomeMethod()
{
Test.Notify<Apple>(AppleHandler);
}
private void AppleHandler(Fruit fruit)
{
Apple apple = (Apple)fruit;
}
Is this kind of thing possible?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是你想要的吗?
is this what you want?
您有充分的理由不能这样做。假设你的方法的其余部分是:
那肯定行不通,所以编译器在这里是正确的。
There is good reason you cannot do this. Suppose the rest of your method was:
That would definitely not work, so the compiler is correct here.
像这样的事情怎么办?
例如,如果使用
Banana
参数调用AppleHandler
,则FruitDelegate
实例在调用时会抛出 InvalidCastException。What about something like this?
The
FruitDelegate
instance, when invoked, would throw an InvalidCastException if, say, anAppleHandler
was invoked with aBanana
argument.