私はこの方法を持っています
public string DictionaryToString<T, U>(Dictionary<T, U> dict)
{
var valueStrings = dict.Select(x => x.Key.ToString() + ": " + x.Value.ToString());
return String.Join("\n", valueStrings);
}
そして、私はそれに渡したいこのオブジェクトを持っています
if ((value !=null) && value.GetType().IsGenericType &&
value.GetType().GetGenericTypeDefinition() == typeof (Dictionary<,>))
{
var castValue = value as Dictionary<,>; // this cast does not work
return DictionaryToString(castValue);
}
else
{
return value.ToString();
}
.Net 4.5 でこのようなリフレクション コードを使用できます
var targetMethodInfo = typeof(MyType).GetMethod("DictionaryToString");
var valueTypeArgs = value.GetType().GenericTypeArguments;
var genericMethod = targetMethodInfo.MakeGenericMethod(valueTypeArgs);
var result = genericMethod.Invoke(this, new[] {value });
return result.ToString();
しかしType.GenericTypeArguments
、.Net 4.5 の新機能です。では、.Net 4.0 でそのキャストを行うにはどうすればよいでしょうか。