2016-07-29 46 views
-1

我有以下類...是否可以將以下類組合成單個泛型類?

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

是的,你可以使用泛型做到這一點:

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

這並不編譯。 – Enigmativity

+0

@Enigmativity現在應該編譯。 – TheAuzzieJesus

+0

@TheAuzzieJesus - 你應該讓羅伯特修復自己的答案。 – Enigmativity

相關問題