问题描述
这会产生一个错误,提示我无法转换类型 ClassType
到 T
.有什么解决方法吗?
This generates an error saying I cannot convert type ClassType
to T
. Is there any workaround for this?
有没有办法指定实际上可以将 this
的类型转换为 T
的类型?
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);
}
推荐答案
两种可能的解决方案:
不是类型安全的:
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);
}
}
这里的要点是为了能够将 this
强制转换为 T
,编译器希望确保 this
始终可转换为 T
(因此需要约束).如非类型安全的示例所示,与泛型一起使用的经典"(不安全)解决方案正在通过类型转换传递给 object
.
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
.
这篇关于将对象转换为方法泛型类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!