Я изо всех сил пытаюсь определить структуру моих классов
Я создал список объектов класса ObjMetaClass
. Который содержит некоторую мета-информацию о своем объекте points
(points
: свойство класса ObjMetaClass
).
Но points
может быть двух типов: один TwoPointsPattern
класс и два других ThreePointsPattern
class
Меня беспокоит то, что всякий раз, когда я хочу получить доступ к какому-либо предмету, мне сначала нужно проверить, какой предмет хранится в текущем предмете для каста (это TwoPointsPattern
или ThreePointsPattern
)
List<ObjMetaClass> objList = new List<ObjMetaClass>();
// some items
objList.Add(new ObjMetaClass(new TwoPointsPattern(...), isTwoPointsPattern:true, rate:124));
objList.Add(new ObjMetaClass(new ThreePointsPattern(...), isTwoPointsPattern:false, rate:654));
// access items from list
for (int i = 0; i < objList.Count; i++)
{
// check for casting object
if(objList[i].isTwoPointsPattern)
TwoPointsPattern temp = objList[i].points as TwoPointsPattern;
/* some logic or function call */
else
ThreePointsPattern temp = objList[i].points as ThreePointsPattern;
/* some logic or function call */
}
Есть ли лучший способ улучшить его или избежать if
проверок? Любые предложения, пожалуйста
Структуры классов
ObjMetaClass
public class ObjMetaClass
{
public object points { get; internal set; }
public bool isTwoPointsPattern { get; internal set; }
internal int rate { get; set; }
public ObjMetaClass(object points, bool isTwoPointsPattern, int rate)
{
// check expected type of points object
if (points.GetType() != typeof(TwoPointsPattern) &&
points.GetType() != typeof(ThreePointsPattern))
throw new ArgumentException("Expected types TwoPointsPattern and ThreePointsPattern");
this.points = points;
this.isTwoPointsPattern = isTwoPointsPattern;
this.rate = rate;
}
}
TwoPointsPattern и ThreePointsPattern
public class TwoPointsPattern
{
public double FirstDate { get; internal set; }
public double FirstPrice { get; internal set; }
public double SecondDate { get; internal set; }
public double SecondPrice { get; internal set; }
public TwoPointsPattern(double FirstDate, double FirstPrice, double SecondDate, double SecondPrice)
{
this.FirstDate = FirstDate; this.FirstPrice = FirstPrice;
this.SecondDate = SecondDate; this.SecondPrice = SecondPrice;
}
}
public class ThreePointsPattern
{
public double FirstDate { get; internal set; }
public double FirstPrice { get; internal set; }
public double SecondDate { get; internal set; }
public double SecondPrice { get; internal set; }
public double ThirdDate { get; internal set; }
public double ThirdPrice { get; internal set; }
public ThreePointsPattern(double FirstDate, double FirstPrice, double SecondDate, double SecondPrice,
double ThirdDate, double ThirdPrice)
{
this.FirstDate = FirstDate; this.FirstPrice = FirstPrice;
this.SecondDate = SecondDate; this.SecondPrice = SecondPrice;
this.ThirdDate = ThirdDate; this.ThirdPrice = ThirdPrice;
}
}