1 // Licensed to the .NET Foundation under one or more agreements.
2 // The .NET Foundation licenses this file to you under the MIT license.
3 // See the LICENSE file in the project root for more information.
4 
5 using System.Xml;
6 using System.Reflection;
7 
8 namespace System.Runtime.Serialization
9 {
10 #if USE_REFEMIT || uapaot
11     public sealed class KnownTypeDataContractResolver : DataContractResolver
12 #else
13     internal sealed class KnownTypeDataContractResolver : DataContractResolver
14 #endif
15     {
16         private XmlObjectSerializerContext _context;
17 
KnownTypeDataContractResolver(XmlObjectSerializerContext context)18         internal KnownTypeDataContractResolver(XmlObjectSerializerContext context)
19         {
20             Fx.Assert(context != null, "KnownTypeDataContractResolver should not be instantiated with a null context");
21             _context = context;
22         }
23 
TryResolveType(Type type, Type declaredType, DataContractResolver knownTypeResolver, out XmlDictionaryString typeName, out XmlDictionaryString typeNamespace)24         public override bool TryResolveType(Type type, Type declaredType, DataContractResolver knownTypeResolver, out XmlDictionaryString typeName, out XmlDictionaryString typeNamespace)
25         {
26             if (type == null)
27             {
28                 typeName = null;
29                 typeNamespace = null;
30                 return false;
31             }
32             if (declaredType != null && declaredType.IsInterface && CollectionDataContract.IsCollectionInterface(declaredType))
33             {
34                 typeName = null;
35                 typeNamespace = null;
36                 return true;
37             }
38 
39             DataContract contract = DataContract.GetDataContract(type);
40             if (_context.IsKnownType(contract, contract.KnownDataContracts, declaredType))
41             {
42                 typeName = contract.Name;
43                 typeNamespace = contract.Namespace;
44                 return true;
45             }
46             else
47             {
48                 typeName = null;
49                 typeNamespace = null;
50                 return false;
51             }
52         }
53 
ResolveName(string typeName, string typeNamespace, Type declaredType, DataContractResolver knownTypeResolver)54         public override Type ResolveName(string typeName, string typeNamespace, Type declaredType, DataContractResolver knownTypeResolver)
55         {
56             if (typeName == null || typeNamespace == null)
57                 return null;
58             return _context.ResolveNameFromKnownTypes(new XmlQualifiedName(typeName, typeNamespace));
59         }
60     }
61 }
62