forked from Unity-Technologies/UnityCsReference
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBaseTypeFactory.cs
More file actions
88 lines (75 loc) · 2.56 KB
/
Copy pathBaseTypeFactory.cs
File metadata and controls
88 lines (75 loc) · 2.56 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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using System.Collections.Generic;
using System.Linq;
namespace UnityEditor.Experimental.UIElements.GraphView
{
public abstract class BaseTypeFactory<TKey, TValue>
{
private readonly Dictionary<Type, Type> m_Mappings = new Dictionary<Type, Type>();
private readonly Type m_FallbackType;
private static readonly Type k_KeyType;
private static readonly Type k_ValueType;
static BaseTypeFactory()
{
k_KeyType = typeof(TKey);
k_ValueType = typeof(TValue);
}
public Type this[Type t]
{
get
{
try
{
return m_Mappings[t];
}
catch (KeyNotFoundException e)
{
throw new KeyNotFoundException("Type " + t.Name + " is not registered in the factory.", e);
}
}
set
{
if (!t.IsSubclassOf(k_KeyType) && !t.GetInterfaces().Contains(k_KeyType))
{
throw new ArgumentException("The type passed as key (" + t.Name + ") does not implement or derive from " + k_KeyType.Name + ".");
}
if (!value.IsSubclassOf(k_ValueType))
{
throw new ArgumentException("The type passed as value (" + value.Name + ") does not derive from " + k_ValueType.Name + ".");
}
m_Mappings[t] = value;
}
}
public virtual TValue Create(TKey key)
{
Type valueType = null;
Type keyType = key.GetType();
while (valueType == null && keyType != null && keyType != typeof(TKey))
{
if (!m_Mappings.TryGetValue(keyType, out valueType))
{
keyType = keyType.BaseType;
}
}
if (valueType == null)
{
valueType = m_FallbackType;
}
return InternalCreate(valueType);
}
protected BaseTypeFactory()
: this(typeof(TValue))
{}
protected BaseTypeFactory(Type fallbackType)
{
m_FallbackType = fallbackType;
}
protected virtual TValue InternalCreate(Type valueType)
{
return (TValue)Activator.CreateInstance(valueType);
}
}
}