以下是我正在使用的课程。
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);
}
}
是否有一些聪明的方法可以通过将它应用于基类并仍然将派生类作为输出来重复派生类中的operator +?
答案 0 :(得分:0)
我现在没有C#编译器,但我试着用心去写。尝试使用Generic Type Param,类似的东西:
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)
{
}
}
也许有帮助:
Pass An Instantiated System.Type as a Type Parameter for a Generic Class
http://www.dotnetperls.com/generic
https://msdn.microsoft.com/en-us/library/ms379564(v=vs.80).aspx