データを内部的に格納するコレクションのインターフェイスを作成しようとしています。JObject
internal class JsonDataSet : IDataSet
{
private JObject Document { get; set; }
// The following methods are from the IDataSet interface
public int Count { ... }
public void Add<T>(string key, T value) { ... }
public T GetItem<T>(string key) { ... }
public bool ContainsKey(string key) { ... }
}
メソッドでは、カスタム型に注釈Add<T>
がない場合に便利な例外を提供したいと考えています。DataContract
たとえば、誰かが次のように呼び出した場合:
dataSet.Add<IDictionary<string, IList<CustomType>>>(dict);
適切な注釈がない"Cannot serialize type 'CustomType'. DataContract annotations not found."
場合、例外がスローされます。CustomType
これまでのところ、型定義ですべてのジェネリック引数を取得する方法を見つけたので、それらを確認できます。
private IEnumerable<Type> GetGenericArgumentsRecursively(Type type)
{
if (!type.IsGenericType) yield return type;
foreach (var genericArg in type.GetGenericArguments())
foreach (var yieldType in GetGenericArgumentsRecursively(genericArg ))
yield return yieldType;
}
そして、次のように add メソッドを実装しようとしました:
public void Add<T>(string key, T value)
{
foreach(var type in GetGenericArgumentsRecursively(typeof(T)))
{
if(!type.IsPrimitive && !Attribute.IsDefined(type, typeof(DataContractAttribute)))
throw new Exception("Cannot serialize type '{0}'. DataContract annotations not found.", typeof(T));
}
Document.Add(new JProperty(key, JToken.Parse(JsonConvert.SerializeObject(value))));
}
これは、プリミティブ型とカスタム型では機能すると思いますが、非ジェネリックな .NET 型にはすべてのDataContract
注釈があるわけではないため、機能しません。によってシリアル化できる型を知る方法はありJsonConvert
ますか?