[英]Inherit from generic type as interface
I am attempting to do something similar to: 我试图做类似的事情:
public interface IView<T> : T where T : class
{
T SomeParam {get;}
}
So that i can later do 这样我以后就可以了
public class SomeView : IView<ISomeView>
{
}
Is it possible to specify inheritance using generics in this way or do i have to go the long way round and explicitly specify both interfaces when defining the class and do: 是否有可能以这种方式使用泛型指定继承,或者我必须走很长的路并在定义类时显式指定两个接口并执行:
public interface IView<T>
{
T SomeParam {get;}
}
public class SomeView : IView<ISomeView>, ISomeView
{
}
This isn't possible, but your goal may be achievable with conversion operators . 这是不可能的,但你的目标可能是实现转换操作符 。 It seems that what you're trying to do is make it possible to pass an
IView<T>
as the T
object which it contains. 看来你要做的就是将
IView<T>
作为它包含的T
对象传递成为可能。 You could write a base class like this: 你可以写一个这样的基类:
public abstract class ViewBase<T> {
public abstract T SomeParam { get; }
public static implicit operator T(ViewBase<T> view) {
return view.SomeParam;
}
}
Then, if you define a class like: 然后,如果你定义一个类,如:
public class SomeView : ViewBase<ISomeView> { }
It can be accepted anywhere an ISomeView
is expected: 它可以在任何需要
ISomeView
地方接受:
ISomeView view = new SomeView();
Short answer: It is not possible. 简短的回答:这是不可能的。 See this post
看这篇文章
An Interface can't derive from a class
. 接口不能从
class
派生。 However nothing prevent you from doing this: 但是没有什么能阻止你这样做:
public interface ISomeView
{
}
public interface IView<out T> where T:class
{
T SomeParam { get; }
}
public class SomeView:IView<ISomeView>
{
public ISomeView SomeParam { get; set; }
}
Edit: 编辑:
If you don't want to implement the T SomeParam { get; }
如果你不想实现
T SomeParam { get; }
T SomeParam { get; }
each time you need to have an implementation, Does this would work? T SomeParam { get; }
每次你需要有一个实施时间,这是否会工作?
public interface ISomeView
{
}
public abstract class BaseView<T> where T : class
{
public T SomeParam { get; set; }
}
public class SomeView : BaseView<ISomeView>{
}
In both case this would work: 在这两种情况下,这都可行:
public class main
{
public class OneOfThoseView : ISomeView
{
}
public main()
{
OneOfThoseView oneOfThose = new OneOfThoseView();
SomeView x = new SomeView();
x.SomeParam = oneOfThose;
}
}
Edit 2: Not exactly what you want to do but this would force your SomeView class to return a BaseView<SomeView>
class 编辑2:不完全是你想要做的,但这会强制你的SomeView类返回一个
BaseView<SomeView>
类
public interface ISomeView
{
}
public abstract class BaseView<T> where T : BaseView<T>
{
public T SomeParam { get; set; }
}
public class SomeView : BaseView<SomeView>
{
}
Now only this would work. 现在只有这个可行。
public main()
{
SomeView y= new SomeView ();
SomeView x = new SomeView();
x.SomeParam = y;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.