简体   繁体   English

C# - 将泛型委托转换为非泛型委托

[英]C# - Casting a Generic Delegate to a Non Generic Delegate

I have a generic delegate that accepts a argument, Args<T> .我有一个通用委托,它接受一个参数Args<T> I also have a normal delegate which accepts Args .我也有一个接受Args的普通委托。

delegate Task ExampleDelegate<T>(Args<T> args)

delegate Task ExampleDelegate(Args args)

Args<T> extends from Args Args<T>Args扩展

public class Args {

}

public class Args<T> : Args {

}

I am currently extending my non generic interfaces/classes which use ExampleDelegate to create new generic interfaces/classes using ExampleDelegate<T> .我目前正在扩展我的非通用接口/类,它们使用ExampleDelegate创建新的通用接口/类使用ExampleDelegate<T>

Since all of them extend the non-generic versions, it has been painless to extend them so far until I had to override a method which accepts ExampleDelegate .由于它们都扩展了非通用版本,因此在我不得不覆盖接受ExampleDelegate的方法之前,扩展它们一直很ExampleDelegate

I haven't been able to cast ExampleDelegate<T> into ExampleDelegate since the signatures don't match.由于签名不匹配,我无法将ExampleDelegate<T>转换为ExampleDelegate

One of the ways I was able to this was,我能够做到这一点的方法之一是,

ExampleDelegate<SomeClass> genericDelegate= //some method

//First case
ExampleDelegate nonGenericDelegate = args => genericDelegate(args as Args<SomeClass>);

//Second case
genericDelegate = argsT => nonGenericDelegate(argsT as Args);

Is there any better way of doing this?有没有更好的方法来做到这一点?

I understand why I need to cast in the first case, but I don't see why I need to cast explicitly in the second case as well?我明白为什么我需要在第一种情况下进行强制转换,但我不明白为什么我也需要在第二种情况下进行明确的强制转换? ( Args<T> extends from Args ) Args<T>Args扩展)

Is there any better way of doing this?有没有更好的方法来做到这一点?

Probably yes, but we don't know what you are trying to do so we can't help you可能是的,但我们不知道您要做什么,所以我们无法帮助您

I don't see why I need to cast explicitly in the second case as well?我不明白为什么我也需要在第二种情况下显式转换?

You don't...?你不……? Here is some code that compiles just fine:这是一些编译得很好的代码:

class TestClass
{
    void DoStuff()
    {
        ExampleDelegate nonGeneric = a => { };
        ExampleDelegate<int> generic = b => nonGeneric(b);
    }
}

delegate void ExampleDelegate(Args args);

delegate void ExampleDelegate<T>(Args<T> args);

class Args<T> : Args {}

class Args {}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM