さまざまな種類のデータに関するデータをグラフ化するのに十分柔軟なクラスを設計しようとしています。私は C# で OOP を初めて使用するので、ジェネリック、デリゲート、およびクラスの組み合わせを使用してこれを達成しようと手探りしています。
これまでに書いたクラスは次のとおりです。
using System;
using System.Collections.Generic;
namespace Charting
{
public class DataChart<T>
{
public Func<T, object> RowLabel { get; set; }
}
}
そして、これが私がそれを呼び出そうとしている方法です:
var model = new DataChart<MyClass>()
{
RowLabel = delegate(MyClass row)
{
return String.Format("{0}-hello-{1}", row.SomeColumn, row.AnotherColumn);
}
};
このアプローチの問題は、RowLabelによって発行されたオブジェクトを明示的にキャストする必要があることです。次のように、何らかの方法で出力タイプをジェネリックにして、それに制約を追加できることを望んでいました。
public class DataChart<T>
{
// The output of the RowLabel method can only be a value type (e.g. int, decimal, float) or string.
public Func<T, U> RowLabel where U : struct, string { get; set; }
}
これは可能ですか?もしそうなら、どうすればいいですか?前もって感謝します!