[英]C#. How can I use a method described in a base class with the arguments of inherited class?
Lets imagine the following structure of classes: 让我们想象一下类的以下结构:
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{}
Is it safety to use method like this : 使用这种方法是否安全:
B b = new B();
B[] arr = new B[2];
b.MiddlePoint(arr);
? ? If not, what should I do to make this method call safety except overloading it in the class B? 如果不是,除了在B类中重载此方法外,我应该怎么做才能使此方法安全? It is not convenient every time overload this method in every inherited class. 每次在每个继承的类中重载此方法都是不方便的。
PS Safety means without throwing exception in any case. PS安全意味着在任何情况下都不会抛出异常。
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. 就像您创建一个类型为A
的新数组,然后将数组中每个B
实例向上转换为A
并插入该数组中。 After pass that array of A
type objects to the method. 将那个A
类型对象数组传递给方法之后。
So this is as it intended to work. 所以这就是它的预期目的。
More on this you can find on: Covariance and Contravariance 有关更多信息,请参见 : 协方差和协方差
Yes, your code should work in C#. 是的,您的代码应在C#中运行。 (At least, something like it compiles on my machine under C# 4.0, once you add a no-arg constructor to A
.). (至少,一旦向A
添加无参数构造函数,类似的东西就会在我的计算机上的C#4.0下编译。)
Your code as written will return an instance of A
when passed in an array of any subtype of A
. 书面将返回的实例代码A
中的任何亚型的数组过去了A
。 If you insist on, for example, getting back an instance of B
instead when you pass in an array of B
, you could use generics, similar to the following: 例如,如果您坚持要在传递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{}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.