Why does the constructor overload in Funky<T>
have an issue with the action parameter but the subclass FunkyAction
does not?
class Funky<T>
{
readonly T _data;
public Funky(T data)
{
_data = data;
}
public Funky(Action action, bool imJustAnOverload)
: this(action) // cannot convert from 'System.Action' to 'T'
{
}
}
class FunkyAction : Funky<Action>
{
public FunkyAction(Action action)
: base(action) // no compile error
{
}
}
This constructor:
public Funky(Action action, bool imJustAnOverload)
: this(action)
is trying to use this constructor:
public Funky(T data)
passing an Action
as a argument to a parameter of type T
.
Since T
is a generic type paremeter, then the compiler cannot guarantee that action
can be casted to T
. As far as the compiler is concerned, T
could be an int
or a string
.
Now, for the derived class, this constructor:
public FunkyAction(Action action)
: base(action)
Is trying to use this base class constructor:
public Funky(T action)
But since it is defining T
as Action
(in class FunkyAction : Funky<Action>
), then the base constructor actually looks like this (from the perspective of FunkyAction
in specific):
public Funky(Action action)
Now there is no problem passing an argument of type Action
to a method that expects an Action
.
You could make the base class constructor generic like this:
public Funky(T action, bool imJustAnOverload)
: this(action)
{
}
That will allow you to create a Funky<Action>
and construct it with an Action
like this:
Funky<Action> funky = new Funky<Action>(() => DoSomething(), true);
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments