是否可以将以下类合并为一个通用类

本文关键字:一个 合并 是否 | 更新日期: 2023-09-27 17:59:18

我有以下类。。。

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)把这两个类组合成一个类吗?

我想这样做是因为以后可能会有更多的课程我的项目需要修改这些类的格式(例如,每个类都有一个字母和一个值,对应于某个情况)

是否可以将以下类合并为一个通用类

是的,你可以用泛型来做这件事:

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}";
}