Why can't I add a delegate to my interface?
相关问题
- Sorting 3 numbers without branching [closed]
- Graphics.DrawImage() - Throws out of memory except
- Generic Generics in Managed C++
- Why am I getting UnauthorizedAccessException on th
- 求获取指定qq 资料的方法
A Delegate is just another type, so you don't gain anything by putting it inside the interface.
You shouldn't need to create your own delegates. Most of the time you should just use EventHandler, Func, Predicate, or Action.
May I ask what your delegate looks like?
An interface method can accept a delegate as a parameter, no issues. (Maybe I'm not seeing the problem?) But if the intention is to specify an outbound call in the interface, use an event.
There are so many little details, it's a lot easier to just show some code instead of trying to describe it all in prose. (Sorry, even the code sample is a bit bloated...)
You can use any of these:
As others have mentioned, you can only define delegates outside of the interface.
There is little to nothing wrong w/ using delegates. Personally I think that
Func<int, double>
is less desirable than using delegates:It is old news that Events are not thread safe, thus the following code is not ideal:
See: http://kristofverbiest.blogspot.com/2006/08/better-way-to-raise-events.html
The safer code is:
You have to duplicate the signature of the event if you want to save it to a variable (or you could use
var
, which I dislike). If you have lots of arguments then this could get very tedious (again, you could always be lazy and usevar
).Delegates save you from having to duplicate the signature of the method/event every time you want to assign it to a variable type.
The documentation clearly says that you can define a delegate in an interface:
MSDN: interface (C# Reference)
However, in the remarks on the same page it says that an interface can contain signatures of methods, properties, indexers and events.
If you try to put a delegate in an interface, the compiler says that "interfaces cannot declare types."
The Ecma-334 standard (8.9 Interfaces) agrees with the remarks on that page and the compiler.
this is a delegate TYPE decalaration...
this cant be declared in an interface as it is a type declaration
however using the type declaration above you CAN use a delegate instance
so delegate instances are OK but delegate type declarations aren't (in an interface)