System.Collections.Generic.Dictionary.ContainsKey(System.Type)

Here are the examples of the csharp api System.Collections.Generic.Dictionary.ContainsKey(System.Type) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

1557 Examples 7

19 Source : Formatter.Array1.Type.Helper.cs
with MIT License
from 1996v

public static bool IsArray1Type(Type t)
        {
            return _array1ItemTypes.ContainsKey(t);
        }

19 Source : DbContext.cs
with MIT License
from 2881099

public virtual IDbSet Set(Type enreplacedyType) {
			if (_dicSet.ContainsKey(enreplacedyType)) return _dicSet[enreplacedyType];
			var sd = Activator.CreateInstance(typeof(DbContextDbSet<>).MakeGenericType(enreplacedyType), this) as IDbSet;
			if (enreplacedyType != typeof(object)) _dicSet.Add(enreplacedyType, sd);
			return sd;
		}

19 Source : InternalExtensions.cs
with MIT License
from 2881099

static bool IsNumberType(this Type that) => that == null ? false : _dicIsNumberType.Value.ContainsKey(that);

19 Source : AObjectBase.cs
with MIT License
from 404Lcc

public T GetComponent<T>() where T : AObjectBase
        {
            Type type = typeof(T);
            if (_componentDict.ContainsKey(type))
            {
                AObjectBase aObjectBase = _componentDict[type];
                return (T)aObjectBase;
            }
            return null;
        }

19 Source : AObjectBase.cs
with MIT License
from 404Lcc

public T AddComponent<T>(params object[] datas) where T : AObjectBase
        {
            Type type = typeof(T);
            if (_componentDict.ContainsKey(type))
            {
                Debug.LogError("Component已存在" + type.FullName);
                return null;
            }
            T aObjectBase = ObjectBaseFactory.Create<T>(this, datas);
            _componentDict.Add(typeof(T), aObjectBase);
            return aObjectBase;
        }

19 Source : AObjectBase.cs
with MIT License
from 404Lcc

public T AddComponent<T, P1>(P1 p1, params object[] datas) where T : AObjectBase
        {
            Type type = typeof(T);
            if (_componentDict.ContainsKey(type))
            {
                Debug.LogError("Component已存在" + type.FullName);
                return null;
            }
            T aObjectBase = ObjectBaseFactory.Create<T, P1>(this, p1, datas);
            _componentDict.Add(typeof(T), aObjectBase);
            return aObjectBase;
        }

19 Source : AObjectBase.cs
with MIT License
from 404Lcc

public T AddComponent<T, P1, P2>(P1 p1, P2 p2, params object[] datas) where T : AObjectBase
        {
            Type type = typeof(T);
            if (_componentDict.ContainsKey(type))
            {
                Debug.LogError("Component已存在" + type.FullName);
                return null;
            }
            T aObjectBase = ObjectBaseFactory.Create<T, P1, P2>(this, p1, p2, datas);
            _componentDict.Add(typeof(T), aObjectBase);
            return aObjectBase;
        }

19 Source : AObjectBase.cs
with MIT License
from 404Lcc

public T AddComponent<T, P1, P2, P3>(P1 p1, P2 p2, P3 p3, params object[] datas) where T : AObjectBase
        {
            Type type = typeof(T);
            if (_componentDict.ContainsKey(type))
            {
                Debug.LogError("Component已存在" + type.FullName);
                return null;
            }
            T aObjectBase = ObjectBaseFactory.Create<T, P1, P2, P3>(this, p1, p2, p3, datas);
            _componentDict.Add(typeof(T), aObjectBase);
            return aObjectBase;
        }

19 Source : AObjectBase.cs
with MIT License
from 404Lcc

public T AddComponent<T, P1, P2, P3, P4>(P1 p1, P2 p2, P3 p3, P4 p4, params object[] datas) where T : AObjectBase
        {
            Type type = typeof(T);
            if (_componentDict.ContainsKey(type))
            {
                Debug.LogError("Component已存在" + type.FullName);
                return null;
            }
            T aObjectBase = ObjectBaseFactory.Create<T, P1, P2, P3, P4>(this, p1, p2, p3, p4, datas);
            _componentDict.Add(typeof(T), aObjectBase);
            return aObjectBase;
        }

19 Source : AObjectBase.cs
with MIT License
from 404Lcc

public void RemoveComponent(AObjectBase aObjectBase)
        {
            if (IsDisposed)
            {
                return;
            }
            if (_componentDict == null)
            {
                return;
            }
            Type type = aObjectBase.GetType();
            if (_componentDict.ContainsKey(type))
            {
                _componentDict[type].Dispose();
                _componentDict.Remove(type);
            }
        }

19 Source : AObjectBase.cs
with MIT License
from 404Lcc

public void RemoveComponent<T>() where T : AObjectBase
        {
            if (IsDisposed)
            {
                return;
            }
            if (_componentDict == null)
            {
                return;
            }
            Type type = typeof(T);
            if (_componentDict.ContainsKey(type))
            {
                _componentDict[type].Dispose();
                _componentDict.Remove(type);
            }
        }

19 Source : KVS.cs
with MIT License
from 7Bytes-Studio

private static IKeyValueStorage CheckImplOrReturn(Type type)
        {
            if (!s_ImplDic.ContainsKey(type))
            {
                s_ImplDic.Add(type,Utility.Reflection.New(type) as IKeyValueStorage);
            }
            return s_ImplDic[type];
        }

19 Source : ObjectPool.PoolFactoryBinder.partial.cs
with MIT License
from 7Bytes-Studio

public void Bind(Type objectType,PoolFactoryCallback poolFactoryCallback)
            {
                if (!m_BindDic.ContainsKey(objectType))
                {
                    m_BindDic.Add(objectType,poolFactoryCallback);
                    return;
                }
                throw new System.Exception(string.Format("类型'{0}'已经绑定过了!请务重新绑定!",objectType));
            }

19 Source : ObjectPool.PoolFactoryBinder.partial.cs
with MIT License
from 7Bytes-Studio

public PoolFactoryCallback GetBinding(Type objectType)
            {
                if (m_BindDic.ContainsKey(objectType))
                {
                    return m_BindDic[objectType];
                }
                return null;
            }

19 Source : Organize.Command.partial.cs
with MIT License
from 7Bytes-Studio

public static void SetCommandPermission<T>(int permission) where T : Event.IEventHandler
            {
                if (!s_CommandPermissonDic.ContainsKey(typeof(T)))
                {
                    s_CommandPermissonDic.Add(typeof(T), permission);
                    return;
                }
                s_CommandPermissonDic[typeof(T)] = permission;
            }

19 Source : Organize.Command.partial.cs
with MIT License
from 7Bytes-Studio

public static int GetCommandPermission<T>() where T : Event.IEventHandler
            {
                if (s_CommandPermissonDic.ContainsKey(typeof(T)))
                {
                    return s_CommandPermissonDic[typeof(T)];
                }
                return int.MaxValue;
            }

19 Source : Inspector.cs
with GNU General Public License v3.0
from a2659802

private static void _reflectProps(Type t, BindingFlags flags = BindingFlags.Public | BindingFlags.Instance)
        {
            if (cache_prop.ContainsKey(t))
                return;
            var propInfos =t.GetProperties(flags)
                .Where(x =>
                {
                    var handlers = x.GetCustomAttributes(typeof(HandleAttribute), true).OfType<HandleAttribute>();
                    bool handflag = handlers.Any();
                    bool ignoreflag = x.GetCustomAttributes(typeof(InspectIgnoreAttribute), true).OfType<InspectIgnoreAttribute>().Any();
                    if(handflag && (!ignoreflag))
                    {
                        if(!handler.ContainsKey(x))
                            handler.Add(x, handlers.FirstOrDefault().handleType);
                    }

                    return handflag && (!ignoreflag);
                });
            foreach(var p in propInfos)
            {
                if(cache_prop.TryGetValue(t,out var npair))
                {
                    npair.Add(p.Name, p);
                }
                else
                {
                    var d = new Dictionary<string, PropertyInfo>();
                    d.Add(p.Name, p);
                    cache_prop.Add(t, d);
                }

                //Logger.LogDebug($"Cache PropInfo:T:{t},name:{p.Name}");
            }
            //Logger.LogDebug($"_reflectProp_resutl:{propInfos.ToArray().Length}");
        }

19 Source : UMAAssetIndexer.cs
with Apache License 2.0
from A7ocin

void ISerializationCallbackReceiver.OnAfterDeserialize()
        {
            var st = StartTimer();
            #region typestuff
            List<System.Type> newTypes = new List<System.Type>()
        {
        (typeof(SlotDatareplacedet)),
        (typeof(OverlayDatareplacedet)),
        (typeof(RaceData)),
        (typeof(UMATextRecipe)),
        (typeof(UMAWardrobeRecipe)),
        (typeof(UMAWardrobeCollection)),
        (typeof(RuntimeAnimatorController)),
#if UNITY_EDITOR
        (typeof(AnimatorController)),
#endif
        (typeof(DynamireplacedADnareplacedet)),
        (typeof(Textreplacedet))
        };

            TypeToLookup = new Dictionary<System.Type, System.Type>()
        {
        { (typeof(SlotDatareplacedet)),(typeof(SlotDatareplacedet)) },
        { (typeof(OverlayDatareplacedet)),(typeof(OverlayDatareplacedet)) },
        { (typeof(RaceData)),(typeof(RaceData)) },
        { (typeof(UMATextRecipe)),(typeof(UMATextRecipe)) },
        { (typeof(UMAWardrobeRecipe)),(typeof(UMAWardrobeRecipe)) },
        { (typeof(UMAWardrobeCollection)),(typeof(UMAWardrobeCollection)) },
        { (typeof(RuntimeAnimatorController)),(typeof(RuntimeAnimatorController)) },
#if UNITY_EDITOR
        { (typeof(AnimatorController)),(typeof(RuntimeAnimatorController)) },
#endif
        {  typeof(Textreplacedet), typeof(Textreplacedet) },
        { (typeof(DynamireplacedADnareplacedet)), (typeof(DynamireplacedADnareplacedet)) }
        };

            List<string> invalidTypeNames = new List<string>();
            // Add the additional Types.
            foreach (string s in IndexedTypeNames)
            {
                if (s == "")
                    continue;
                System.Type sType = System.Type.GetType(s);
                if (sType == null)
                {
                    invalidTypeNames.Add(s);
                    Debug.LogWarning("Could not find type for " + s);
                    continue;
                }
                newTypes.Add(sType);
                if (!TypeToLookup.ContainsKey(sType))
                {
                    TypeToLookup.Add(sType, sType);
                }
            }

            Types = newTypes.ToArray();

            if (invalidTypeNames.Count > 0)
            {
                foreach (string ivs in invalidTypeNames)
                {
                    IndexedTypeNames.Remove(ivs);
                }
            }
            BuildStringTypes();
            #endregion
            UpdateSerializedDictionaryItems();
            StopTimer(st, "Before Serialize");
        }

19 Source : Inspector.cs
with GNU General Public License v3.0
from a2659802

public static void Show()
        {
            OpLock.Apply();
            try
            {
                Item item = ItemManager.Instance.currentSelect.GetComponent<CustomDecoration>().item;
                

                if (!cache_prop.ContainsKey(item.GetType()))
                {
                    _reflectProps(item.GetType());
                }
                if (cache_prop.TryGetValue(item.GetType(), out var itemProps))
                {
                    var insp = new InspectPanel();
                    currentEdit = insp;
                    int idx = 0;
                    foreach (var kv in itemProps)
                    {
                        string name = kv.Key;
                        Type propType = kv.Value.PropertyType;
                        object value = kv.Value.GetValue(item, null);
                        value = Convert.ToSingle(value);
                        ConstraintAttribute con = kv.Value.GetCustomAttributes(typeof(ConstraintAttribute), true).OfType<ConstraintAttribute>().FirstOrDefault();

                        LogProp(propType, name, value);

                        if(idx == 0)
                        {
                            insp.UpdateName(idx,name);
                            if(con is IntConstraint)
                            {
                                //Logger.LogDebug($"Check1 {con.Min}-{con.Max}");
                                insp.UpdateSliderConstrain(name,idx, (float)Convert.ChangeType(con.Min, typeof(float)), Convert.ToInt32(con.Max), true);
                            }
                            else if(con is FloatConstraint)
                            {
                                //Logger.LogDebug($"Check2 {con.Min}-{con.Max}");
                                insp.UpdateSliderConstrain(name,idx, (float)(con.Min), (float)(con.Max), false);
                            }
                            else
                            {
                                throw new ArgumentException();
                            }
                            //Logger.LogDebug($"Check3 {value}-{value.GetType()}");
                            insp.UpdateValue(idx, (float)value);
                        }
                        else
                        {
                            insp.AppendPropPanel(name);
                            if (con is IntConstraint)
                            {
                                insp.UpdateSliderConstrain(name,idx, (int)con.Min, (int)con.Max, true);
                            }
                            else if (con is FloatConstraint)
                            {
                                insp.UpdateSliderConstrain(name,idx, (float)con.Min, (float)con.Max, false);
                            }
                            else
                            {
                                throw new ArgumentException();
                            }
                            insp.UpdateValue(idx, (float)value);
                            insp.UpdateTextDelegate(idx);//insp.AddListener(idx, insp.UpdateTextDelegate(idx));

                        }
                        //insp.AddListener(idx, (v) => { kv.Value.SetValue(item, Convert.ChangeType(v, kv.Value.PropertyType), null); });
                        insp.AddListener(idx, (v) => {
                            if (ItemManager.Instance.currentSelect == null)
                                return;
                            object val;
                            try
                            {
                                if (kv.Value.PropertyType.IsSubclreplacedOf(typeof(Enum)))
                                {
                                    val = Enum.Parse(kv.Value.PropertyType, v.ToString("0"));
                                }
                                else
                                    val = Convert.ChangeType(v, kv.Value.PropertyType);
                                ItemManager.Instance.currentSelect.GetComponent<CustomDecoration>().Setup(handler[kv.Value], val);
                            }
                            catch
                            {
                                Logger.LogError("Error occour at Inspect OnValue Chnaged");
                                Hide();
                            }
                        });
                        idx++;
                    }
                }
                else
                {
                    Logger.LogError($"KeyNotFount at cache_prop,{item.GetType()}");
                }
                
            }
            catch(NullReferenceException e)
            {
                Logger.LogError($"NulRef Error at Inspector.Show:{e}");
                OpLock.Undo();
            }
       
        }

19 Source : UMAAssetIndexerEditor.cs
with Apache License 2.0
from A7ocin

public bool ShowArray(System.Type CurrentType, string Filter)
		{
			bool HasFilter = false;
			bool NotFound = false;
			string actFilter = Filter.Trim().ToLower();
			if (actFilter.Length > 0)
				HasFilter = true;

			Dictionary<string, replacedereplacedem> TypeDic = UAI.GetreplacedetDictionary(CurrentType);

			if (!TypeCheckboxes.ContainsKey(CurrentType))
			{
				TypeCheckboxes.Add(CurrentType, new List<bool>());
			}

			List<replacedereplacedem> Items = new List<replacedereplacedem>();
			Items.AddRange(TypeDic.Values);

			int NotInBuild = 0;
			int VisibleItems = 0;
			foreach (replacedereplacedem ai in Items)
			{
				if (ai._SerializedItem == null)
				{
					NotInBuild++;
				}
				string Displayed = ai.ToString(UMAreplacedetIndexer.SortOrder);
				if (HasFilter && (!Displayed.ToLower().Contains(actFilter)))
				{
					continue;
				}
				VisibleItems++;
			}

			if (TypeCheckboxes[CurrentType].Count != VisibleItems)
			{
				TypeCheckboxes[CurrentType].Clear();
				TypeCheckboxes[CurrentType].AddRange(new bool[VisibleItems]);
			}

			NotInBuildCount += NotInBuild;
			GUILayout.BeginHorizontal(EditorStyles.toolbarButton);
			GUILayout.Space(10);
			Toggles[CurrentType] = EditorGUILayout.Foldout(Toggles[CurrentType], CurrentType.Name + ":  "+VisibleItems+ "/" + TypeDic.Count + " Item(s). "+NotInBuild+" Not in build.");
			GUILayout.EndHorizontal();



			if (Toggles[CurrentType])
			{
				Items.Sort();
				GUIHelper.BeginVerticalPadded(5, new Color(0.75f, 0.875f, 1f));
				GUILayout.BeginHorizontal();
				GUILayout.Label("Sorted By: " + UMAreplacedetIndexer.SortOrder, GUILayout.MaxWidth(160));
				foreach (string s in UMAreplacedetIndexer.SortOrders)
				{
					if (GUILayout.Button(s, GUILayout.Width(80)))
					{
						UMAreplacedetIndexer.SortOrder = s;
					}
				}
				GUILayout.EndHorizontal();

				int CurrentVisibleItem = 0;
				foreach (replacedereplacedem ai in Items)
				{
					string lblBuild = "B-";
					string lblVal = ai.ToString(UMAreplacedetIndexer.SortOrder);
					if (HasFilter && (!lblVal.ToLower().Contains(actFilter)))
						continue;

					if (ai._Name == "< Not Found!>")
					{
						NotFound = true;
					}
					GUILayout.BeginHorizontal(EditorStyles.textField);

					TypeCheckboxes[CurrentType][CurrentVisibleItem] = EditorGUILayout.Toggle(TypeCheckboxes[CurrentType][CurrentVisibleItem++],GUILayout.Width(20));
					if (ai._SerializedItem == null)
					{
						lblVal += "<Not in Build>";
						lblBuild = "B+";
					}

					if (GUILayout.Button(lblVal /* ai._Name + " (" + ai._replacedetBaseName + ")" */, EditorStyles.label))
					{
						EditorGUIUtility.PingObject(replacedetDatabase.LoadMainreplacedetAtPath(ai._Path));
					}

					if (GUILayout.Button(lblBuild,GUILayout.Width(35)))
					{
						if (ai._SerializedItem == null)
						{
							if (!ai.IsreplacedetBundle)
								ai.CachSerializedItem();
						}
						else
						{
							ai.ReleaseItem();
						}

					}
					if (GUILayout.Button("-", GUILayout.Width(20.0f)))
					{
						DeletedDuringGUI.Add(ai);
					}
					GUILayout.EndHorizontal();
				}

				GUILayout.BeginHorizontal();
				if (NotFound)
				{
					GUILayout.Label("Warning - Some items not found!");
				}
				else
				{
					GUILayout.Label("All Items appear OK");
				}
				GUILayout.EndHorizontal();
				if (CurrentType == typeof(SlotDatareplacedet) || CurrentType == typeof(OverlayDatareplacedet))
				{
					GUIHelper.BeginVerticalPadded(5, new Color(0.65f, 0.65f, 0.65f));
					GUILayout.Label("Utilities");
					GUILayout.Space(10);

					EditorGUILayout.BeginHorizontal();
					if (GUILayout.Button("Select All"))
					{
						ProcessItems(CurrentType, null, HasFilter, actFilter, Items, Selecreplacedems);
					}
					if (GUILayout.Button("Select None"))
					{
						ProcessItems(CurrentType, null, HasFilter, actFilter, Items, Deselecreplacedems);
					}
					EditorGUILayout.EndHorizontal();
					EditorGUILayout.BeginHorizontal();
					if (GUILayout.Button("Remove Checked"))
					{
						ProcessItems(CurrentType, TypeCheckboxes[CurrentType], HasFilter, actFilter, Items, RemoveChecked);
					}
					EditorGUILayout.EndHorizontal();



					EditorGUILayout.BeginHorizontal();
					SelectedMaterial = (UMAMaterial)EditorGUILayout.ObjectField(SelectedMaterial, typeof(UMAMaterial), false);
					GUILayout.Label("Apply to checked: ");
					if (GUILayout.Button("Unreplacedigned"))
					{
						ProcessItems(CurrentType, TypeCheckboxes[CurrentType], HasFilter, actFilter, Items, SereplacedemNullMaterial);
					}
					if (GUILayout.Button("All"))
					{
						ProcessItems(CurrentType, TypeCheckboxes[CurrentType], HasFilter, actFilter, Items, SereplacedemMaterial);
					}
					EditorGUILayout.EndHorizontal();
					GUIHelper.EndVerticalPadded(5);
				}

				GUIHelper.EndVerticalPadded(5);
			}
			return NotFound;
		}

19 Source : UMAAssetIndexer.cs
with Apache License 2.0
from A7ocin

private void CreateLookupDictionary(System.Type type)
        {
            Dictionary<string, replacedereplacedem> dic = new Dictionary<string, replacedereplacedem>();
            if (TypeLookup.ContainsKey(type))
            {
                TypeLookup[type] = dic;
            }
            else
            {
                TypeLookup.Add(type, dic);
            }
        }

19 Source : UMAAssetIndexer.cs
with Apache License 2.0
from A7ocin

public Dictionary<string, replacedereplacedem> GetreplacedetDictionary(System.Type type)
        {
            System.Type LookupType = TypeToLookup[type];
            if (TypeLookup.ContainsKey(LookupType) == false)
            {
                TypeLookup[LookupType] = new Dictionary<string, replacedereplacedem>();
            }
            return TypeLookup[LookupType];
        }

19 Source : RaceData.cs
with Apache License 2.0
from A7ocin

public void UpdateDictionary()
	    {
	        raceDictionary.Clear();
	        for (int i = 0; i < dnaConverterList.Length; i++)
	        {
	            if (dnaConverterList[i])
	            {
                    dnaConverterList[i].Prepare();
	                if (!raceDictionary.ContainsKey(dnaConverterList[i].DNAType))
	                {
	                    raceDictionary.Add(dnaConverterList[i].DNAType, dnaConverterList[i].ApplyDnaAction);
	                }
	            }
	        }
	    }

19 Source : MixedRealityServiceRegistry.cs
with Apache License 2.0
from abist-co-ltd

private static bool TryGetServiceInternal(Type interfaceType,
            out IMixedRealityService serviceInstance,
            out IMixedRealityServiceRegistrar registrar,
            string name = null)
        {
            using (TryGetServiceInternalPerfMarker.Auto())
            {
                // replacedume failed and return null unless proven otherwise
                serviceInstance = null;
                registrar = null;

                // If there is an entry for the interface key provided, search that small list first
                if (registry.ContainsKey(interfaceType))
                {
                    if (FindEntry(registry[interfaceType], interfaceType, name, out serviceInstance, out registrar))
                    {
                        return true;
                    }
                }

                // Either there is no entry for the interface type, or it was not placed in that list. 
                // Services can have multiple supported interfaces thus they may match the requested query but be placed in a different registry bin
                // Thus, search all bins until a match is found
                foreach (var list in registry.Values)
                {
                    if (FindEntry(list, interfaceType, name, out serviceInstance, out registrar))
                    {
                        return true;
                    }
                }

                return false;
            }
        }

19 Source : TypeCacheUtility.cs
with Apache License 2.0
from abist-co-ltd

public static List<Type> GetSubClreplacedes(Type baseClreplacedType)
        {
#if !NETFX_CORE
            if (baseClreplacedType == null) { return null; }

            if (!cache.ContainsKey(baseClreplacedType))
            {
                cache[baseClreplacedType] = baseClreplacedType.GetAllSubClreplacedesOf();
            }

            return cache[baseClreplacedType];
#else
            return null;
#endif
        }

19 Source : ServiceFacade.cs
with Apache License 2.0
from abist-co-ltd

public void SetService(IMixedRealityService service)
        {
            this.Service = service;

            if (service == null)
            {
                ServiceType = null;
                name = "(Destroyed)";
                gameObject.SetActive(false);
                return;
            }
            else
            {
                this.ServiceType = service.GetType();

                name = ServiceType.Name;
                gameObject.SetActive(true);

                if (!FacadeServiceLookup.ContainsKey(ServiceType))
                {
                    FacadeServiceLookup.Add(ServiceType, this);
                }
                else
                {
                    FacadeServiceLookup[ServiceType] = this;
                }

                if (!ActiveFacadeObjects.Contains(this))
                {
                    ActiveFacadeObjects.Add(this);
                }
            }
        }

19 Source : CoreServices.cs
with Apache License 2.0
from abist-co-ltd

public static bool ResetCacheReference(Type serviceType)
        {
            if (typeof(IMixedRealityService).IsreplacedignableFrom(serviceType))
            {
                if (serviceCache.ContainsKey(serviceType))
                {
                    serviceCache.Remove(serviceType);
                    return true;
                }
            }
            else
            {
                Debug.Log("Cache only contains types that implement IMixedRealityService");
            }

            return false;
        }

19 Source : CoreServices.cs
with Apache License 2.0
from abist-co-ltd

private static T GetService<T>() where T : IMixedRealityService
        {
            Type serviceType = typeof(T);

            // See if we already have a WeakReference entry for this service type
            if (serviceCache.ContainsKey(serviceType))
            {
                IMixedRealityService svc;
                // If our reference object is still alive, return it
                if (serviceCache[serviceType].TryGetTarget(out svc))
                {
                    return (T)svc;
                }

                // Our reference object has been collected by the GC. Try to get the latest service if available
                serviceCache.Remove(serviceType);
            }

            // This is the first request for the given service type. See if it is available and if so, add entry
            T service;
            if (!MixedRealityServiceRegistry.TryGetService(out service))
            {
                return default(T);
            }

            serviceCache.Add(typeof(T), new WeakReference<IMixedRealityService>(service, false));
            return service;
        }

19 Source : MixedRealityServiceRegistry.cs
with Apache License 2.0
from abist-co-ltd

public static bool AddService<T>(T serviceInstance, IMixedRealityServiceRegistrar registrar) where T : IMixedRealityService
        {
            if (serviceInstance == null)
            {
                // Adding a null service instance is not supported.
                return false;
            }

            if (serviceInstance is IMixedRealityDataProvider)
            {
                // Data providers are generally not used by application code. Services that intend for clients to
                // directly communicate with their data providers will expose a GetDataProvider or similarly named
                // method.
                return false;
            }

            Type interfaceType = typeof(T);
            T existingService;

            if (TryGetService<T>(out existingService, serviceInstance.Name))
            {
                return false;
            }

            // Ensure we have a place to put our newly registered service.
            if (!registry.ContainsKey(interfaceType))
            {
                registry.Add(interfaceType, new List<KeyValuePair<IMixedRealityService, IMixedRealityServiceRegistrar>>());
            }

            List<KeyValuePair<IMixedRealityService, IMixedRealityServiceRegistrar>> services = registry[interfaceType];
            services.Add(new KeyValuePair<IMixedRealityService, IMixedRealityServiceRegistrar>(serviceInstance, registrar));
            AddServiceToCache(serviceInstance, registrar);
            return true;
        }

19 Source : MixedRealityServiceRegistry.cs
with Apache License 2.0
from abist-co-ltd

private static bool RemoveServiceInternal(
            Type interfaceType,
            IMixedRealityService serviceInstance,
            IMixedRealityServiceRegistrar registrar)
        {
            if (!registry.ContainsKey(interfaceType)) { return false; }

            List<KeyValuePair<IMixedRealityService, IMixedRealityServiceRegistrar>> services = registry[interfaceType];

            bool removed = services.Remove(new KeyValuePair<IMixedRealityService, IMixedRealityServiceRegistrar>(serviceInstance, registrar));

            if (services.Count == 0)
            {
                // If the last service was removed, the key can be removed.
                registry.Remove(interfaceType);
            }

            RemoveServiceFromCache(serviceInstance, registrar);

            return removed;
        }

19 Source : BaseServiceManager.cs
with Apache License 2.0
from abist-co-ltd

public bool RegisterService<T>(T serviceInstance) where T : IMixedRealityService
        {
            Type interfaceType = typeof(T);

            if (registeredServices.ContainsKey(interfaceType))
            {
                Debug.LogError($"Failed to register {serviceInstance} service. There is already a registered service implementing {interfaceType}");
                return false;
            }

            bool registered = MixedRealityServiceRegistry.AddService<T>(serviceInstance, this);
            if (registered)
            {
                registeredServices.Add(interfaceType, serviceInstance);
            }

            return registered;
        }

19 Source : BaseServiceManager.cs
with Apache License 2.0
from abist-co-ltd

public bool UnregisterService<T>(T serviceInstance) where T : IMixedRealityService
        {
            if (serviceInstance == null) { return false; }

            Type interfaceType = typeof(T);
            if (!registeredServices.ContainsKey(interfaceType)) { return false; }

            registeredServices.Remove(interfaceType);
            return MixedRealityServiceRegistry.RemoveService<T>(serviceInstance, this);
        }

19 Source : SettingsPopup.vm.cs
with MIT License
from Accelerider

private async void OpenDialog<T>() where T : new()
        {
            var type = typeof(T);

            if (!_dialogDictionary.ContainsKey(type))
                _dialogDictionary[type] = new T();

            _view.SetValue(System.Windows.Controls.Primitives.Popup.IsOpenProperty, false);
            await DialogHost.Show(_dialogDictionary[type], "RootDialog");
        }

19 Source : BlockDownloadItemPolicy.cs
with MIT License
from Accelerider

public BlockDownloadItemPolicy Catch<TException>(BlockDownloadItemExceptionHandler<TException> handler)
            where TException : Exception
        {
            var type = typeof(TException);
            if (_handlers.ContainsKey(type))
                throw new ArgumentException($"A handler that handles {typeof(TException)} exceptions already exists. ");

            _handlers[type] = (e, retryCount, context) => handler((TException)e, retryCount, context);
            return this;
        }

19 Source : ModEntry.cs
with GNU General Public License v3.0
from aedenthorn

public static Monster BossHere(GameLocation location)
        {
            using (List<NPC>.Enumerator enumerator = location.characters.GetEnumerator())
            {
                while (enumerator.MoveNext())
                {
                    NPC j = enumerator.Current;
                    if (BossTypes.ContainsKey(j.GetType()))
                    {
                        return (Monster)j;
                    }
                }
            }
            return null;
        }

19 Source : ModEntry.cs
with GNU General Public License v3.0
from aedenthorn

private void OnDayEnding(object sender, DayEndingEventArgs e)
        {
            foreach (GameLocation location in Game1.locations)
            {
                for (int i = 0; i < location.characters.Count; i++)
                {
                    if (BossTypes.ContainsKey(location.characters[i].GetType()) || location.characters[i] is ToughFly || location.characters[i] is ToughGhost)
                    {
                        location.characters.RemoveAt(i);
                    }

                }
            }        
            foreach (GameLocation location in Game1._locationLookup.Values)
            {
                for (int i = 0; i < location.characters.Count; i++)
                {
                    if (BossTypes.ContainsKey(location.characters[i].GetType()) || location.characters[i] is ToughFly || location.characters[i] is ToughGhost)
                    {
                        location.characters.RemoveAt(i);
                    }

                }
            }
        }

19 Source : PacketChannel.cs
with MIT License
from afxw

public void RegisterHandler<TPacket>(Action<PaceClient, IPacket> handler)
        {
            if (Handlers.ContainsKey(typeof(TPacket)))
            {
                Handlers.Remove(typeof(TPacket));
            }

            Handlers.Add(typeof(TPacket), handler);
        }

19 Source : PacketChannel.cs
with MIT License
from afxw

public void RegisterHandler<TPacket>(Action<IPacket> handler)
        {
            if (Handlers.ContainsKey(typeof(TPacket)))
            {
                Handlers.Remove(typeof(TPacket));
            }

            Handlers.Add(typeof(TPacket), handler);
        }

19 Source : DependencyObjects.cs
with Mozilla Public License 2.0
from agebullhu

public void Annex<T>(T value)
        {
            Type type = typeof(T);
            if (_dictionary.ContainsKey(type))
            {
                if (Equals(value, default(T)))
                {
                    _dictionary.Remove(type);
                }
                else
                {
                    _dictionary[type] = value;
                }
            }
            else if (!Equals(value, default(T)))
            {
                _dictionary.Add(type, value);
            }
        }

19 Source : PluginManager.cs
with GNU General Public License v2.0
from afrantzis

public static PluginManager GetForType(Type pluginType)
	{
		PluginManager ret = null;
		
		if (pluginManagers.ContainsKey(pluginType)) {
			ret = pluginManagers[pluginType];
		}
		
		return ret;
	}

19 Source : IDataExtendChecker.cs
with Mozilla Public License 2.0
from agebullhu

public static void Regist<TDataExtendChecker, TTargetType>()
            where TDataExtendChecker : clreplaced, IDataExtendChecker, new() where TTargetType : clreplaced
        {
            var distType = typeof(TTargetType);
            if (!Checker.TryGetValue(distType, out var list))
                Checker.Add(distType, list = new ExtendCheckers
                {
                    Convert = arg => (object)(arg as TTargetType)
                });
            if (list.Dictionary.ContainsKey(typeof(TDataExtendChecker)))
                return;
            list.Dictionary.Add(typeof(TDataExtendChecker), () => new TDataExtendChecker());
        }

19 Source : EnumHelper.cs
with Mozilla Public License 2.0
from agebullhu

public static List<IEnumInfomation> GetEnumInfomation(Type type)
        {
            if (type == null)
            {
                return new List<IEnumInfomation>();
            }
            if (EnumInfomationMaps.ContainsKey(type))
            {
                return EnumInfomationMaps[type];
            }

            var enumFieldInfos = type.GetFields();
            var kvs = enumFieldInfos.Where(p => p.Name != "value__").Select(fieldInfo => (IEnumInfomation)new EnumInfomation
            {
                Caption = fieldInfo.GetDescription(),
                Value = Enum.Parse(type, fieldInfo.Name, true),
                LValue = Convert.ToInt64(Enum.Parse(type, fieldInfo.Name, true))
            }).ToList();

            EnumInfomationMaps.Add(type, kvs);

            return kvs;
        }

19 Source : DependencyObjects.cs
with Mozilla Public License 2.0
from agebullhu

public void Annex<T>(T value)
        {
            var type = typeof(T);
            if (_dictionary.ContainsKey(type))
            {
                if (Equals(value, default(T)))
                {
                    _dictionary.Remove(type);
                }
                else
                {
                    _dictionary[type] = value;
                }
            }
            else if (!Equals(value, default(T)))
            {
                _dictionary.Add(type, value);
            }
        }

19 Source : DependencyFunctions.cs
with Mozilla Public License 2.0
from agebullhu

public bool HaseDelegate<TAction>() where TAction : clreplaced
        {
            return _dictionary.ContainsKey(typeof(TAction));
        }

19 Source : DependencyObjects.cs
with Mozilla Public License 2.0
from agebullhu

public void Annex<T>(T value)
        {
            Type type = typeof (T);
            if (_dictionary.ContainsKey(type))
            {
                if (Equals(value, default( T )))
                {
                    _dictionary.Remove(type);
                }
                else
                {
                    _dictionary[type] = value;
                }
            }
            else if (!Equals(value, default( T )))
            {
                _dictionary.Add(type, value);
            }
        }

19 Source : FunctionDictionaryBase.cs
with Mozilla Public License 2.0
from agebullhu

public void AnnexDelegate<TAction>(TAction action, string name = null) where TAction : clreplaced
        {
            if (string.IsNullOrEmpty(name))
            {
                var type = typeof(TAction);
                if (_dependencyDictionary.ContainsKey(type))
                {
                    if (Equals(action, null))
                    {
                        _dependencyDictionary.Remove(type);
                    }
                    else
                    {
                        _dependencyDictionary[type] = action;
                    }
                }
                else if (!Equals(action, null))
                {
                    _dependencyDictionary.Add(type, action);
                }
            }
            else if (_nameDictionary.ContainsKey(name))
            {
                if (Equals(action, null))
                {
                    _nameDictionary.Remove(name);
                }
                else
                {
                    _nameDictionary[name] = action;
                }
            }
            else if (!Equals(action, null))
            {
                _nameDictionary.Add(name, action);
            }
        }

19 Source : FunctionDictionaryBase.cs
with Mozilla Public License 2.0
from agebullhu

public bool HaseDelegate<TAction>(string name = null) where TAction : clreplaced
        {
            return name == null
                ? _dependencyDictionary.ContainsKey( typeof(TAction)) 
                : _nameDictionary.ContainsKey(name);
        }

19 Source : DependencyFunctions.cs
with Mozilla Public License 2.0
from agebullhu

public void AnnexDelegate<TAction>(TAction action) where TAction : clreplaced
        {
            var type = typeof(TAction);
            if (_dictionary.ContainsKey(type))
            {
                if (Equals(action, null))
                {
                    _dictionary.Remove(type);
                }
                else
                {
                    _dictionary[type] = action as Delegate;
                }
            }
            else if (!Equals(action, null))
            {
                _dictionary.Add(type, action as Delegate);
            }
        }

19 Source : CommandCoefficient.cs
with Mozilla Public License 2.0
from agebullhu

public static void RegisterCommand(ICommandItemBuilder builder)
        {
            var type = builder.TargetType ?? typeof(object);
            if (CommandBuilders.ContainsKey(type))
            {
                CommandBuilders[type].Add(builder);
            }
            else
            {
                CommandBuilders.Add(type, new List<ICommandItemBuilder> { builder });
            }
        }

19 Source : CommandsNextExtension.cs
with MIT License
from Aiko-IT-Systems

public async Task<object> ConvertArgument<T>(string value, CommandContext ctx)
#pragma warning restore IDE1006 // Naming Styles
        {
            var t = typeof(T);
            if (!this.ArgumentConverters.ContainsKey(t))
                throw new ArgumentException("There is no converter specified for given type.", nameof(T));

            if (this.ArgumentConverters[t] is not IArgumentConverter<T> cv)
                throw new ArgumentException("Invalid converter registered for this type.", nameof(T));

            var cvr = await cv.ConvertAsync(value, ctx).ConfigureAwait(false);
            return !cvr.HasValue ? throw new ArgumentException("Could not convert specified value to given type.", nameof(value)) : cvr.Value;
        }

See More Examples