おはようございます、
辞書を持つクラス Product{} があります。
Dictionary<Type, List<IPropertyItem>> extensions;
この方法でデータを保存します。
public void SaveItem<T>(T item)
{
Type currentType = typeof(T);
if (!extensions.ContainsKey(currentType))
{
extensions.Add(currentType, new List<IPropertyItem>());
}
if (currentType == typeof(Discount))
{
Discount newDiscount = (Discount)Convert.ChangeType(item, typeof(Discount));
extensions[currentType].Add(newDiscount);
}
else if(currentType == typeof(Tax))
{
Tax newTax = (Tax)Convert.ChangeType(item, typeof(Tax));
extensions[currentType].Add(newTax);
}
else if(currentType == typeof(Size))
{
Size newSize = (Size)Convert.ChangeType(item, typeof(Size));
extensions[currentType].Add(newSize);
}
}
今、私は自分の辞書に保存されている特定の値型のリストを取得したいと思っています。つまり、このメソッドが次の関数のようなリストを返すことを意味します:
public List<T> GetExtensionsDictionary<T>()
{
Type currentType = typeof(T);
List<T> returnedList = new List<T>();
if (!extensions.ContainsKey(currentType))
{
return null;
}
return extensions[T];
}
上記を呼び出しているメソッドは次のとおりです。
List<Discount> myDiscounts = myProduct.GetExtensionsDictionary<Discount>();
トンクス、
どんな助けも感謝します...
私はこれがあなたが望むすべてだと信じています:
public List<T> GetExtensionsDictionary<T>()
{
Type currentType = typeof(T);
List<T> returnedList = new List<T>();
if (!extensions.ContainsKey(currentType))
{
return null;
}
return extensions[currentType].Cast<T>().ToList();
}
はジェネリック パラメーターであり、 で取得するランタイム タイプが必要なためextensions
、currentType
notにインデックスを付ける必要があります。T
T
typeof
linq メソッドCast
とToList
を使用しcurrentType
て、ディクショナリのコレクション atを に変換できList<T>
ます。これはリストのコピーを作成しているため、パフォーマンスに関する考慮事項に注意してください。
いることを確認してください using System.Linq;
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加