1

让我们想象一下类的以下结构:

    class A{
        public double X;
        public double Y;

        public A(double x, double y){
            X=x; Y=y;
        };   
        public A MiddlePoint(A[] a){
            A resultPnt = new A(0,0);
            for (int i = 0; i < a.Length; i++){
                resultPnt.X += a[i].X;
                resultPnt.Y += a[i].Y;
            }
            resultPnt.X = (this.X + resultPnt.X)/(a.Length + 1);
            resultPnt.Y = (this.Y + resultPnt.Y)/(a.Length + 1);
        }
    }

    class B:A{}

使用这样的方法是否安全:

B b = new B();
B[] arr = new B[2];
b.MiddlePoint(arr);

? 如果不是,我应该怎么做才能使这个方法调用安全,除了在 B 类中重载它?每次在每个继承的类中重载此方法都不方便。

PS安全意味着在任何情况下都不会抛出异常。

4

2 回答 2

1

It's like you create a new array of type of A, and every instance of B in your array uppercast to A and insert in that array. After pass that array of A type objects to the method.

So this is as it intended to work.

More on this you can find on: Covariance and Contravariance

于 2013-11-13T10:13:14.640 回答
1

是的,您的代码应该在 C# 中工作。(至少,一旦您将无参数构造函数添加到A.),它就可以在 C# 4.0 下的我的机器上编译。)。

您编写的代码将A在传入任何子类型的数组时返回A. B例如,如果您坚持在传入 的数组时取回 的实例,则B可以使用泛型,类似于以下内容:

class A{
    public double X;
    public double Y;

    public A(double x, double y){
        X=x; Y=y;
    }
    public A(){
        // needs to have a no-arg constructor to satisfy new() constraint on MiddlePoint
    }
    public T MiddlePoint<T>(T[] a) where T : A, new() {
        T resultPnt = new T();
        for (int i = 0; i < a.Length; i++){
            resultPnt.X += a[i].X;
            resultPnt.Y += a[i].Y;
        }
        resultPnt.X = (this.X + resultPnt.X)/(a.Length + 1);
        resultPnt.Y = (this.Y + resultPnt.Y)/(a.Length + 1);
    }
}

class B:A{}
于 2013-11-13T10:17:59.007 回答