2016-07-29 45 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

相关问题