我有以下课程......
LetterScore.cs
public class LetterScore {
public char Letter;
public int Score;
public LetterScore(char c = ' ', int score = 0) {
Letter = c;
Score = score;
}
public override string ToString() => $"LETTER:{Letter}, SCORE:{Score}";
}
LetterPoint.cs
public class LetterPoint {
public char Letter;
public Point Position;
public LetterPoint(char c = ' ', int row = 0, int col = 0) {
Letter = c;
Position = new Point(row, col);
}
public string PositionToString => $"(X:{Position.X}Y:{Position.Y})";
public override string ToString() => $"(LETTER:{Letter}, POSITION:{PositionToString})";
}
我可以使用LINQ
或通用变量(例如T)将这两个类组合成一个类吗?
我希望这样做,因为可能会有更多的课程 我的项目需要改变这些类的格式 (例如,每个类都有一个字母和一个对应于某个特定的值 情况)
答案 0 :(得分:0)
是的,你可以用泛型来做到这一点:
public class Letter<T>
{
public char Letter {get;set;}
public T Item {get;set;} /*or make this protected and expose it in your derived class */
}
public class LetterPoint : Letter<Point>
{
public LetterPoint(char c = ' ', int row = 0, int col = 0)
{
Letter = c;
Item = new Point(row, col);
}
public string PositionToString => $"(X:{Item.X}Y:{Item.Y})";
public override string ToString() => $"(LETTER:{Letter}, POSITION:{PositionToString})";
}
public class LetterScore : Letter<int>
{
public LetterScore(char c = ' ', int score = 0)
{
Letter = c;
Item = score;
}
public override string ToString() => $"LETTER:{Letter}, SCORE:{Item}";
}