简体   繁体   English

C#,将self用作基类的抽象重写方法的参数

[英]C#, Using self as a parameter for an abstract override method of the base class

How would I override DerivedZ() in the child, without having to specify a U in the base class? 如何在子类中重写DerivedZ(),而不必在基类中指定U? The latter solution appears a bit excessive. 后一种解决方案似乎有点过分。

public abstract class Z {}
public class DerivedZ : Z 
{
    public DerivedZ (B someB, int num)
    {
        // initialize here
    }
}

// will not compile
// error: 'B.GetZ(B, int)': no suitable method found to override
// error: 'B' does not implement inherited abstract member 'A<DerivedZ>.GetZ(A<DerivedZ>, int)'
public abstract class A<T> where T : Z
{
    public abstract T GetZ (A<T> inputA, int optional=1);
}

public class B : A<DerivedZ>
{       
    public override DerivedZ GetZ (B someB, int optional=1)
    {
        return new DerivedZ (someB, optional)
    }
}

this works though... 这虽然有效...

public abstract class A<T,U> where T : Z where U : A<T,U>
{
    public abstract T GetZ (U inputA, int optional=1);
}

public class B : A<DerivedZ,B>
{
    public override DerivedZ GetZ (B someB, int optional=1)
    {
        return new DerivedZ (someB, optional);
    }
}

You can't use the first form, because it's not properly overriding the method. 您不能使用第一种形式,因为它没有正确覆盖方法。 If you could do that, imagine this code: 如果可以做到这一点,请想象以下代码:

public class C : A<DerivedZ> {}

A<DerivedZ> x = new B();
x.GetZ(new C());

That should work fine, after all - A<T>.GetZ is just declared to accept an A<T> , and C is a A<DerivedZ> . 毕竟,这应该可以正常工作-刚声明A<T>.GetZ接受A<T> ,而C A<DerivedZ>

The approach you've shown is fine. 您展示的方法很好。

I agree that sometimes it would be useful to be able to say "something of the same type" but it's not part of the C# type system. 我同意有时能够说“相同类型的东西”会很有用,但它不是C#类型系统的一部分。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM