[英]Cast object to method generic type
This generates an error saying I cannot convert type ClassType
to T
. 这会生成一个错误,指出我无法将类型
ClassType
转换为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
? 有什么方法来指定的类型,
this
其实可以转换成T
?
public void WorkWith<T>(Action<T> method)
{
method.Invoke((T)this);
}
public void WorkWith<T>(Action<T> method) where T: ClassType {
method.Invoke((T)this);
}
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). 这里的要点是,为了能够将
this
为T
,编译器希望确保this
总是可以转换为T
(因此需要约束)。 As shown in the not-type-safe example, the "classical" (unsafe) solution used with generics is passing through a cast to object
. 如非类型安全示例所示,与泛型一起使用的“经典”(不安全)解决方案是通过强制转换为
object
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.