无论使用基类还是继承类,都执行操作符
本文关键字:执行 操作符 继承 基类 | 更新日期: 2023-09-27 18:05:16
这是一些看起来像我目前正在使用的类。
public class SomeClass
{
public PropertyAClass A { get; set;}
public PropertyBClass B { get; set;}
public SomeClass (PropertyAClass A, PropertyBClass B)
{
this.A = A;
this.B = B;
}
public static SomeClass operator +(SomeClass a, SomeClass b)
{
return new SomeClass(a.A + b.A, a.b + b.B);
}
}
public class DerivedClass : SomeClass
{
public DerivedClass (PropertyADerivedClass A, PropertyBDerivedClass B) : base(A,B)
{
}
//Operation is the same but I have to repeat the method
public static DerivedClass operator +(DerivedClass a, DerivedClass b)
{
return new DerivedClass(a.A + b.A, a.b + b.B);
}
}
是否有一些聪明的方法,可以使它不重复操作符+在派生类中通过应用它到基类,仍然得到派生类作为输出?
我现在没有c#编译器,但我试着用心写一些东西。尝试使用泛型类型参数,类似于:
using System;
using System.Reflection;
public class SomeClass<T>
{
public PropertyAClass A { get; set;}
public PropertyBClass B { get; set;}
public SomeClass (PropertyAClass A, PropertyBClass B)
{
this.A = A;
this.B = B;
}
public static T operator +(T a, T b)
{
return new T(a.A + b.A, a.b + b.B);
}
}
public class DerivedClass : SomeClass<DerivedClass>
{
public DerivedClass (PropertyADerivedClass A, PropertyBDerivedClass B) : base(A,B)
{
}
}
也许有帮助:
传递实例化的系统。作为泛型类的类型参数的类型
http://www.dotnetperls.com/generichttps://msdn.microsoft.com/en-us/library/ms379564 (v = vs.80) . aspx