2014-12-12 4 views
-1

죄송합니다. 질문이 중복되는 경우 죄송하지만 특정 사례에 대한 해결책을 찾을 수 없습니다. 만드는) 방법을공변량 모음이 작동하지 않습니다.

public interface IPoint {} 
public class GazePoint : IPoint {} 
public Point AvgPoint(IEnumerable<IPoint> locations) {} 

List<GazePoint> gazePoints = new List<GazePoint>(); 
//... 
// this doesn't work: 
Point avg = AvgPoint(gazePoints); 

당신이 그것을 작동하지 않는 이유를 설명하십시오 수 (나는 C# 4.0이 문제를 해결했다 가정하고) 어떻게 내가 AvgPoint (의 서명을 변경할 수 있습니다 코드 블록을 고려하시기 바랍니다 IPoint의 다른 구현을받을 수 있습니다. (gazePoints 컬렉션을 다른 루프 유형으로 캐스팅하지 않으려 고합니다. 큰 루프에 있기 때문에 성능에 대한 우려입니다.

[업데이트] : GazePoint를 구조체로 정의했는데 . 구조체가 여기에 작동하지 않는 이유는 문제의 원인이었다 아직도 모르겠어요

+0

'AvgPoint' 메소드에는 return 문이 없습니다. 실제 문제를 나타내는 샘플 코드를 게시하십시오. –

+2

'작동하지 않는 것 '을 정의 할 수 있습니까? 예외 또는 오류? –

+0

메서드 서명이 정상적으로 작동합니다. 나머지는 어떻게 구현하고 있습니까? –

답변

0

내가 정확한 문제는 당신이 가지고있는,하지만 여기가 나를 위해 일한 방법은 무엇인지 확실하지 않다 :.

먼저 실제 클래스 구현 :

public interface IPoint 
{ 
    int X { get; set; } 
    int Y { get; set; } 
} 

public class Point : IPoint 
{ 
    public int X { get; set; } 
    public int Y { get; set; } 

    public Point() 
    { 
    } 

    public Point(int x, int y) 
    { 
     X = x; 
     Y = y; 
    } 
} 

public class GazePoint : IPoint 
{ 
    public int X { get; set; } 
    public int Y { get; set; } 

    public GazePoint() 
    { 
    } 

    public GazePoint(int x, int y) 
    { 
     X = x; 
     Y = y; 
    } 
} 

그런 다음 실제 AvgPo INT 메소드 구현 : 마지막으로

public static Point AvgPoint(IEnumerable<IPoint> locations) 
{ 
    if (locations == null || !locations.Any()) return new Point(0, 0); 

    return new Point((int) locations.Average(l => l.X), 
     (int) locations.Average(l => l.Y)); 
} 

그리고 몇 가지 검사 : 당신은 같은 것이 일반적인 할 수

당신의 목표는 방법에 전달 된 동일한 유형의 평균을 반환해야하는 경우
public static void Main() 
{ 
    var points = new List<Point> 
    { 
     new Point(1, 2), 
     new Point(3, 4) 
    }; 

    var gazePoints = new List<GazePoint> 
    { 
     new GazePoint(1, 2), 
     new GazePoint(3, 4) 
    }; 

    Point avgPoint = AvgPoint(points); 
    Point avgGazePoint = AvgPoint(gazePoints); 

    Console.WriteLine("Average Point = {0}, {1}", avgPoint.X, avgPoint.Y); 
    Console.WriteLine("Average GazePoint = {0}, {1}", avgGazePoint.X, avgGazePoint.Y); 
} 

, 그래서 :

public static T AvgPoint<T>(IEnumerable<T> locations) where T : IPoint, new() 
{ 
    if (locations == null || !locations.Any()) return new T {X = 0, Y = 0}; 

    return new T {X = (int) locations.Average(l => l.X), 
     Y = (int) locations.Average(l => l.Y)}; 
} 
+0

Rufus, 설명과 전체 코드 작성에 많은 도움을 주셔서 감사합니다! 와우! :-) 아래 나의 대답을 읽어주세요! –

+0

Rufus, 설명과 전체 코드 작성에 많은 도움을 주셔서 감사합니다! 와우! :-) 내 구현은 당신과 정확히 같았습니다. 차이점은 하나 : ** class **가 아닌 ** struct **로 _GazePoint_를 정의했기 때문에 문제의 원인이었습니다. 이제 내 코드는 작동하지만 여전히 왜 그런지 모르겠습니다! 'GazePoint gPoint'와 같은 객체를 정의하고 'gPoint is IPoint'가 true이고 'IPoint iPoint = gPoint as IPoint;'와 같은 객체를 _GazePoint_로 정의하면 문제없이 작동하지만 'List '은 'IEnumerable '으로 변환 할 수 없습니다. 다시 한 번 감사드립니다. –

관련 문제