차트를 생성해야하는 클래스가 있습니다. 차트 시리즈에 대해 서로 다른 유형의 데이터를 사용하는 세 가지 클래스가 있습니다. 나는 이러한 클래스의 단지 특성을 제공 할 것입니다 혼란 :)C# 제네릭을 사용하여 클래스의 개체를 형식 T의 개체로 변환하는 방법?
public class PointBase
{
public decimal X { get; set; }
}
public class Point : PointBase
{
public decimal Y { get; set; }
}
public class Bubble : Point
{
public decimal Size { get; set; }
}
이 세 클래스 차트의 시리즈에서 데이터의 기본 조각으로 사용을 방지하기 위해. 차트 시리즈는 다른 세 클래스 (차트)에서 사전 개체로 표시됩니다. 특정 문제에 집중하기 위해 차트 클래스의 코드를 제공하지 않겠습니다. 다음과 같이 클래스 이름을 제공합니다.
- 좌표 데이터 (기본 데이터로 PointBase 사용).
- ScatterChart (포인트 사용).
- BubbleChart (버블 사용).
나는 모든 차트 클래스에 대해 정확히 같은 알고리즘을 사용하는 다음과 같은 방법을 사용합니다. 그래서 제네릭을 사용하여 메서드를 만들기로했습니다.
public Dictionary<string, T[]> GenerateSeriesDataDictionary<T>(string[] series, string[] categories) where T : PointBase, new()
{
// Create a new Dictionary.
Dictionary<string, T[]> seriesData = new Dictionary<string, T[]>();
// Gets the number of categories and assigns the categoriesNumber variable with the returned value.
int categoriesNumber = categories.Length;
foreach (string serie in series)
{
Dictionary<string, T> categoriesData = (Dictionary<string, T>)GetCategoriesData(serie);
// Create a new array of Ts that will store the data for the current serie.
T[] dataArray = new T[categories.Length];
for (int i = 0; i < categoriesNumber; i++)
{
// If the serie contains a value for the current category, store it in the array.
// Otherwise, set the value of the current element of the array to the default one.
dataArray[i] = categoriesData.ContainsKey(categories[i]) ? categoriesData[categories[i]] : new T();
}
// Add the dataArray to the seriesData Dictionary.
seriesData.Add(serie, dataArray);
}
return seriesData;
}
따라서 위의 방법은 두 개의 문자열 배열을 수신합니다. 첫 번째 문자는 시리즈의 이름을 나타냅니다 (예 : "Tokyo"및 "London"). 두 번째 것은 차트 범주의 이름을 나타냅니다. 예를 들어 월 이름은 "January", "February"등입니다.
이 메서드는 이름을 사용하는 Dictionary 개체를 만들기로되어 있습니다 각 카테고리 (내 경우 - 매달)에 대한 데이터를 나타내는 객체의 대응하는 배열과 키로서의 세리 (serie). 예를 들어, Dictionary의 단일 키 - 값 쌍은 다음과 같아야합니다. 키 : "London"; 값 : 17, 16, 20, 25 (데이터가 각 달의 최대 온도를 나타냄).
저는 기본적으로 선, 산산조각 또는 거품 형 차트 (CoordinateChart, ScatterChart 및 BubbleChart 클래스로 표시)를 만들 때마다 동일한 알고리즘을 실행합니다. 유일한 차이점은 내가 생성하는 사전의 유형입니다.
- CoordinateChart 사전 사용 (문자열을가 PointBase은 [])
- scatterchart에가 Dicitonary 사용 (문자열을 가리키고 [])
- BubbleChart 사전 (문자열, 거품 [])
I를 사용 '<'및 '>'문자가 '('및 ')'로 바뀌었기 때문에 사라졌습니다.
그래서 내가 e 논리는 별도의 메소드에서 Dictionary 객체를 생성 한 다음이 각각의 클래스에서이 메소드를 대체해야합니다.
내 방법은 다음과 같습니다
public virtual Dictionary<string, PointBase> GetCategoriesData(string serie)
{
Dictionary<string, PointBase> categoriesData = sqlResultDataTable.AsEnumerable()
.Where(row => row["City"].ToString() == serie)
.Select(row => new KeyValuePair<string, PointBase>(row["Month"].ToString(), new PointBase(decimal.Parse(row["Temperature"].ToString()))))
.ToDictionary(item => item.Key, item => item.Value);
return categoriesData;
}
이 방법은 기본적으로 시리즈의 "월"과 "온도"값을 나타내는 모든 키 - 값 쌍을 얻는다 (예를 들어, "런던").
코드 재사용을 위해이 모든 작업을 수행하고 있습니다.그렇지 않으면 세 클래스 모두에서 동일한 작업을 수행 할 수 있으며 각 클래스에서 GenerateSeriesDataDictionary 메서드를 개별적으로 구현할 수는 있지만 좋은 접근 방식이라고 생각하지 않습니다.
모든 것은 괜찮지 만, 나는이 줄에 오류를 얻을 :
Dictionary<string, T> categoriesData = (Dictionary<string, T>)GetCategoriesData(serie);
오류 상태의 메시지 '사전 (문자열, T)에 입력 사전 (문자열 된 PointBase)를 변환 할 수 없습니다'. 그들은 내가 무엇을 할 수 :)
사라질 것 때문에
나는, '('및 ')'와 '<'와 '>'문자를 대체?
가 왜 categoriesData 사전을 통해하지 그냥 루프가 .Value가 Point' 또는'사용하여 값을 일치시킬 수'.Value는 거품이다 '당신이 컬렉션을 사용해야 할 때마다? –