问题
This generates an error saying I cannot convert type ClassType
to T
. Is there any workaround for this?
Is there any way to specify that the type of this
can in fact be converted to T
?
public void WorkWith<T>(Action<T> method)
{
method.Invoke((T)this);
}
回答1:
Two possible solutions:
Not type-safe:
public void WorkWith<T>(Action<T> method)
{
method.Invoke((T)(object)this);
}
This isn't typesafe because you can pass it any method that has a single parameter and no return value, like:
WorkWith((string x) => Console.WriteLine(x));
The typesafe "version" (using generic constraints):
public class MyClass
{
public void WorkWith<T>(Action<T> method) where T : MyClass
{
method.Invoke((T)this);
}
}
The point here is that to be able to cast this
to T
, the compiler wants to be sure that this
is always castable to T
(so the need for the constraint). As shown in the not-type-safe example, the "classical" (unsafe) solution used with generics is passing through a cast to object
.
回答2:
public void WorkWith<T>(Action<T> method) where T: ClassType {
method.Invoke((T)this);
}
来源:https://stackoverflow.com/questions/35629885/cast-object-to-method-generic-type