向字典添加通用委托. [英] Adding A generic delegate to a Dictionary .

查看:93
本文介绍了向字典添加通用委托.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在处理C#中的泛型时很费力,以下是我正在使用的代码段

I'' having tough time with handling generics in C#, following is the code snippet that i''m using

public delegate void SyncEventDelegate<TEntity>(TEntity entity, SyncInfo requestInfo);



我需要将此代表添加到字典中



i need to add this delegate to a Dictionary

private Dictionary<Type, SyncEventDelegate<ISynchronizeableEntity>> _delegateCollection;



通过委托进行注册的方法具有以下签名.



the method that passes the the delegate to register has the following signature.

public void Register<TEntity>( SyncEventDelegate<ISynchronizeableEntity> syncEventDelegate) where TEntity : ISynchronizeableEntity



目前它可以正常工作,但是我不确定是否将注册方法签名更改为以下格式,但出现编译器错误.



it''s working fine for the moment , but I have a doubt if i change the register method signature to the following format , i get a compiler error.

public void Register<TEntity>( SyncEventDelegate<TEntity> syncEventDelegate) where TEntity : ISynchronizeableEntity



我认为它应该工作,因为TEntity是从ISynchronizeableEntity派生的,但事实并非如此.

我真的很感谢有人能解释一下.



I thought it should work since TEntity is derived from ISynchronizeableEntity, but it doesn''t.

I really appreciate if someone can explain this.
thanks in advance.

推荐答案

您到底从哪里得到错误?
我创建了一个委托和一个方法寄存器,并带有导致错误的签名.

我认为您的问题是您想要一个接收SyncEventDelegate< TEntity>的寄存器.并尝试将其注册到仍为SyncEventDelegate< ISynchronizeableEntity>
类型的字典中
在这种情况下,就像您要将字符串的Action放入对象的Action中一样.这样做没有有效的方差,就像当您收到对象的操作一样,当只有字符串应该是有效的参数时,您可以将任何对象作为参数传递.
我认为您还应该更改字典的类型,或者,如果不可能,则必须始终将参数作为接口的操作来接收.如果需要,委托调用的方法应进行强制转换.
Where exactly do you get the error?
I created a delegate and a method register with the signature you say that causes the error, and it works.

I think your problem is that you want a Register that receives a SyncEventDelegate<TEntity> and tries to register it in a dictionary that is still of type SyncEventDelegate<ISynchronizeableEntity>

In this case, is like you want to put an Action of string inside an Action of object. There is no valid variance for that, as if you receive the Action of object you can pass any object as parameter, when only strings should be valid parameters.
I think you should also change the type of the dictionary or, if that''s not possible, you will need to always receive the parameter as an action of the interface. If needed, the method called by the delegate should do a cast.


这篇关于向字典添加通用委托.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆