[英]C# - Doesn't allow me to return “this” as a type when interface for type is implemented
I have this: 我有这个:
public class MyClass<T>: IView
{
public View View()
{
return this;
}
public void Render(ViewContext viewContext, System.IO.TextWriter writer)
{
// We should cycle though all supported controls and generate HTML for them.
// What about the validation binding?
typeof(T).GetFields().ToList<FieldInfo>().ForEach(x => writer.WriteLine(x.FieldType + " is called " + x.Name + "</br>"));
}
}
I get an error that it cannot implicitly cast this to a View. 我收到一个错误,它无法将其隐式转换为View。 When I attempt a cast it fails. 当我尝试投射时,它会失败。 Is there any way to do this? 有什么办法吗? Why does it fail? 为什么会失败?
EDIT: View implementation added. 编辑:查看实现添加。 I trimmed too much out of the class. 我在课堂上削减了太多。 I apologize for not posting enough. 抱歉,张贴内容不足。
MyClass<T>
instances are not convertible to View
. MyClass<T>
实例不能转换为View
。 They are only convertible to IView
. 它们只能转换为IView
。 If you want to inherit from View
class, you should just do that. 如果要从View
类继承,则应该这样做。 Implementing a similarly named interface doesn't magically cause the class to inherit from the base type you need: 实现一个类似命名的接口不会神奇地导致该类从您需要的基本类型继承:
public class MyClass<T> : View { ... }
Any of these will work. 这些都可以。
public class MyClass<T>: IView
{
public IView View()
{
return this;
}
}
Or 要么
public class MyClass<T>: IView
{
public MyClass<T> View()
{
return this;
}
}
MyClass is not a View and cannot be returned as one as you try to do. MyClass 不是一个View,并且在您尝试做时不能作为一个View返回。
Please try this: 请尝试以下方法:
public class MyClass<T>: IView
{
public View View()
{
return (MyClass<T>) this;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.