forked from JSONAPIdotNET/JSONAPI.NET
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTypeExtensions.cs
More file actions
63 lines (55 loc) · 2.26 KB
/
TypeExtensions.cs
File metadata and controls
63 lines (55 loc) · 2.26 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
namespace JSONAPI.Extensions
{
public static class TypeExtensions
{
public static bool CanWriteAsJsonApiAttribute(this Type objectType)
{
if (objectType.IsGenericType && objectType.GetGenericTypeDefinition() == typeof (Nullable<>))
objectType = objectType.GetGenericArguments()[0];
return objectType.IsPrimitive
|| typeof (Decimal).IsAssignableFrom(objectType)
|| typeof (Guid).IsAssignableFrom(objectType)
|| typeof (DateTime).IsAssignableFrom(objectType)
|| typeof (DateTimeOffset).IsAssignableFrom(objectType)
|| typeof (String).IsAssignableFrom(objectType)
|| objectType.IsEnum;
}
public static IEnumerable<object> CreateEnumerableInstance(this Type type)
{
Type relType;
if (type.IsGenericType)
{
relType = type.GetGenericArguments()[0];
}
else
{
// Must be an array at this point, right??
relType = type.GetElementType();
}
// Hmm...now we have to create an object that fits this property. This could get messy...
if (!type.IsInterface && !type.IsAbstract)
{
// Whew...okay, just instantiate one of these...
return (IEnumerable<Object>)Activator.CreateInstance(type);
}
// Ugh...now we're really in trouble...hopefully one of these will work:
if (type.IsGenericType)
{
if (type.IsAssignableFrom(typeof(List<>).MakeGenericType(relType)))
{
return (IEnumerable<Object>) Activator.CreateInstance(typeof(List<>).MakeGenericType(relType));
}
if (type.IsAssignableFrom(typeof(HashSet<>).MakeGenericType(relType)))
{
return
(IEnumerable<Object>) Activator.CreateInstance(typeof(HashSet<>).MakeGenericType(relType));
}
//TODO: Other likely candidates??
}
return null;
}
}
}