鉴于这个虚构的例子:
class NonGeneric
{
}
class Generic<T> : NonGeneric
where T : NonGeneric
{
T DoSomething()
{
return this; // **
}
}
Run Code Online (Sandbox Code Playgroud)
我期望它编译:Generic<T>派生自NonGeneric并且T必须是派生类,因此它满足其约束.
我应该能够做到这一点:
NonGeneric obj = new Generic<NonGeneric>();
Run Code Online (Sandbox Code Playgroud)
那么这个指令应该没有问题:
return this;
Run Code Online (Sandbox Code Playgroud)
或者至少这个:
return (T)this;
Run Code Online (Sandbox Code Playgroud)
不幸的是它不起作用,上面的例子没有编译错误:
无法将类型转换
NonGeneric<T>为'T'
我做错了什么,我看不到它,或者只是不被允许?为什么这个?
如果可能的话,我会避免使用我在本文中描述的任何解决方法(反射,动态编译方法等).我也会避免使用dynamic对象(设计决定,我不能改变它).
任何人都可以解释如何让这个工作?我传入了类型名称,正确填充了"t".我只是无法弄清楚如何将objectToCast转换为输入"t".任何帮助表示赞赏.
....
Type t = Type.GetType("castToTypeNameHere");
o = CastTo<t>(objectToCast);
....
private T CastTo<T>(Object obj)
{
return (T)obj;
}
Run Code Online (Sandbox Code Playgroud)
仅供参考,这是我找到的答案:
Type t = Type.GetType(element.Attribute("castToType").Value);
MethodInfo castMethod = this.GetType().GetMethod("CastTo", BindingFlags.Instance | BindingFlags.NonPublic).MakeGenericMethod(t);
object castedObject = castMethod.Invoke(this, new object[] { objectToCast });
Run Code Online (Sandbox Code Playgroud)