Using a default implementation on an interface
If I have an interface
And I now want to have a specialized interface
Can I somehow use the default implementation
GetAttack(){GetAttack(level)}
to implement IAttack
for thingss that are implementing IUpgradableAttack
?13 Replies
If I just put the default implementation inside of
IUpgradableAttack
, then when implementing that interface the compiler tells me I still need to implement GetAttack
(even though there should be a default implementation)i don't understand the question. what do you want to provide a default implementation for
Thanks for answering. Basically what I'd like to do is to have
so that I do not have to implement
GetAttack
when I have already implemented GetAttack(int level)
yes, the way you must implement it is by writing
T IAttack<T>.GetAttack() { ... }
Defining the interface as above works. However, when I implement a struct which implements that interface (and does not implement
GetAttack
), then C#
start bugging methere should be a warning in the code you provided
warning CS0108: 'IUpgradableAttack<T>.GetAttack()' hides inherited member 'IAttack<T>.GetAttack()'. Use the new keyword if hiding was intended.it's telling you what the issue is-- when you write
T GetAttack()
, it is not actually an override. it is just a new method also named GetAttackYup thanks!
Just tried it 🙂
I understood my mistake
thank you for helping!
Maybe one more question in case you know that too. If I now have another method
throws an error, since
GetComponent
is not implemented and it somehow does not manage to use the default implementation from the interface.
Prepending the interface name also does not work. Is there a way to use the default implementation without boxing?there is a way to do it
then use
GetComponent(this)
ah ok haha, if that is the only way I maybe will just write
GetComponent(level)
for the implementationsyeah, it is a lame workaround
ok, nevertheless thank you for answering my questions!
helped me a lot
Ok, sorry for coming back again. I think this is really the last time. Will this incur boxing at runtime when I want to call that function?
Because I will have to now explicitly cast everything as that interface to make it work right?
basically asking if there is any allocation happening
oh. um, for a struct, yeah it will
there's no way to avoid it. the
this
inside of the DIM is IUpgradeableAttack
hmm ok thats unfortunate
then I'm just gonna copy paste the implementation of
GetComponent(){ return GetComponent(level);}
I guess