/////////////////////////////////////////////////////////////////////// /// <summary>Replaces or adds an extension of the given type /// to the list. /// /// This method looks for the first element on the list of the /// given type and replaces it with the new value. If there are /// no element of this type yet, a new element is added at the /// end of the list. /// </summary> /// <param name="extensionElements">list of IExtensionElement</param> /// <param name="type">type of the element to be added, removed /// or replaced</param> /// <param name="newValue">new value for this element, null to /// remove it</param> /////////////////////////////////////////////////////////////////////// public static void SetExtension(IList<IExtensionElementFactory> extensionElements, Type type, IExtensionElementFactory newValue) { int count = extensionElements.Count; for (int i = 0; i < count; i++) { object element = extensionElements[i]; if (type.IsInstanceOfType(element)) { if (newValue == null) { extensionElements.RemoveAt(i); } else { extensionElements[i] = newValue; } return; } } if (newValue != null) { extensionElements.Add(newValue); } }
bool IRemotingTypeInfo.CanCastTo(System.Type targetType, object o) { // Console.WriteLine ("CanCastTo: " + targetType); // if this is a local servant, check it directly if (_realObject != null) { return(targetType.IsInstanceOfType(_realObject)); } // check if the thing was created with a valid type if (targetType.IsInstanceOfType(o)) { return(true); } // otherwise, perform the remote query if necessary string icename = IceUtil.TypeToIceName(targetType); if (_typeIds == null) { Ice.Object iob = o as Ice.Object; _typeIds = iob.ice_ids(); } return(((IList)_typeIds).Contains(icename)); }
public static object Annotation(object annotations, Type type) { Guard.NotNull(() => type, type); if (annotations != null) { var annotationsArray = annotations as object[]; if (annotationsArray == null) { if (type.IsInstanceOfType(annotations)) return annotations; } else { for (int i = 0; i < annotationsArray.Length; i++) { var value = annotationsArray[i]; if (value == null) break; if (type.IsInstanceOfType(value)) return value; } } } return null; }
public static object ReadFile_(string file, Type expectedType, IProgressMonitor monitor) { bool clearLoadedPrjList = AlreadyLoadedPackages == null; if (clearLoadedPrjList) AlreadyLoadedPackages = new List<string> (); if (AlreadyLoadedPackages.Contains (file)) return null; AlreadyLoadedPackages.Add (file); DubProject defaultPackage; try{ using (var s = File.OpenText (file)) using (var r = new JsonTextReader (s)) defaultPackage = ReadPackageInformation(file, r, monitor); }catch(Exception ex){ if (clearLoadedPrjList) AlreadyLoadedPackages = null; monitor.ReportError ("Couldn't load dub package \"" + file + "\"", ex); return null; } if (expectedType.IsInstanceOfType (defaultPackage)) { LoadDubProjectReferences (defaultPackage, monitor); if (clearLoadedPrjList) AlreadyLoadedPackages = null; return defaultPackage; } var sln = new DubSolution(); if (!expectedType.IsInstanceOfType (sln)) { if (clearLoadedPrjList) AlreadyLoadedPackages = null; return null; } sln.RootFolder.AddItem(defaultPackage, false); sln.StartupItem = defaultPackage; // Introduce solution configurations foreach (var cfg in defaultPackage.Configurations) sln.AddConfiguration(cfg.Name, false).Platform = cfg.Platform; LoadDubProjectReferences (defaultPackage, monitor, sln); sln.LoadUserProperties(); if (clearLoadedPrjList) { AlreadyLoadedPackages = null; // Clear 'dub list' outputs DubReferencesCollection.DubListOutputs.Clear (); } return sln; }
/// <summary> /// Get the first parent node of the node <code>node</code> that implements the given type <code>type.</code>. /// </summary> /// <param name="node">The node from where the search begins.</param> /// <param name="type">The type to search for.</param> /// <returns>The first parental node that implements the type <code>type.</code> /// </returns> public static object GetRootNodeImplementing(IDocumentNode node, System.Type type) { object root = node.ParentObject; while (root != null && root is IDocumentNode && !type.IsInstanceOfType(root)) { root = ((IDocumentNode)root).ParentObject; } return(type.IsInstanceOfType(root) ? root : null); }
/// Get the value from a target public T Get <T>(object target) { if (Type.IsInstanceOfType(target)) { if (_finfo != null) { return((T)_finfo.GetValue(target)); } if (_pinfo != null) { return((T)_pinfo.GetValue(target, null)); } } return(default(T)); }
/// <summary> /// Get the first parent node of the node <code>node</code> that implements the given type <code>type.</code>. /// </summary> /// <param name="node">The node from where the search begins.</param> /// <param name="type">The type to search for.</param> /// <returns>The first parental node that implements the type <code>type.</code> /// </returns> public static IDocumentLeafNode GetRootNodeImplementing(IDocumentLeafNode node, System.Type type) { if (null == node) { return(null); } node = node.ParentObject; while (node != null && !type.IsInstanceOfType(node)) { node = node.ParentObject; } return(type.IsInstanceOfType(node) ? node : null); }
/// <summary> /// Gets the extension object declared by this node /// </summary> /// <param name="expectedType"> /// Expected object type. An exception will be thrown if the object is not an instance of the specified type. /// </param> /// <returns> /// The extension object /// </returns> /// <remarks> /// The extension object is cached and the same instance will be returned at every call. /// </remarks> public object GetInstance (Type expectedType) { object ob = GetInstance (); if (!expectedType.IsInstanceOfType (ob)) throw new InvalidOperationException (string.Format ("Expected subclass of type '{0}'. Found '{1}'.", expectedType, ob.GetType ())); return ob; }
/// <inheritdoc /> protected override object ConvertImpl(object sourceValue, Type targetType) { if (sourceValue == null || targetType.IsInstanceOfType(sourceValue)) return sourceValue; throw new InvalidOperationException("The null converter does not support conversions."); }
internal static StateFileBase DeserializeCache(string stateFile, TaskLoggingHelper log, Type requiredReturnType) { StateFileBase o = null; try { if (((stateFile == null) || (stateFile.Length <= 0)) || !File.Exists(stateFile)) { return o; } using (FileStream stream = new FileStream(stateFile, FileMode.Open)) { object obj2 = new BinaryFormatter().Deserialize(stream); o = obj2 as StateFileBase; if ((o == null) && (obj2 != null)) { log.LogMessageFromResources("General.CouldNotReadStateFileMessage", new object[] { stateFile, log.FormatResourceString("General.IncompatibleStateFileType", new object[0]) }); } if ((o != null) && !requiredReturnType.IsInstanceOfType(o)) { log.LogWarningWithCodeFromResources("General.CouldNotReadStateFile", new object[] { stateFile, log.FormatResourceString("General.IncompatibleStateFileType", new object[0]) }); o = null; } } } catch (Exception exception) { log.LogWarningWithCodeFromResources("General.CouldNotReadStateFile", new object[] { stateFile, exception.Message }); } return o; }
private void ValidateObjectParamater( SerializedProperty arguments, PersistentListenerMode mode) { SerializedProperty propertyRelative1 = arguments.FindPropertyRelative("m_ObjectArgumentAssemblyTypeName"); SerializedProperty propertyRelative2 = arguments.FindPropertyRelative("m_ObjectArgument"); UnityEngine.Object objectReferenceValue = propertyRelative2.objectReferenceValue; if (mode != PersistentListenerMode.Object) { propertyRelative1.stringValue = typeof(UnityEngine.Object).AssemblyQualifiedName; propertyRelative2.objectReferenceValue = (UnityEngine.Object)null; } else { if (objectReferenceValue == (UnityEngine.Object)null) { return; } System.Type type = System.Type.GetType(propertyRelative1.stringValue, false); if (typeof(UnityEngine.Object).IsAssignableFrom(type) && type.IsInstanceOfType((object)objectReferenceValue)) { return; } propertyRelative2.objectReferenceValue = (UnityEngine.Object)null; } }
object ChangeType(object value, Type targetType) { if (targetType.IsInstanceOfType(value)) return value; if (targetType == typeof(string)) { try { return value.ToString(); } catch { } } if (value != DBNull.Value) { try { return System.Convert.ChangeType(value, targetType); } catch { } } if (targetType != typeof(object)) { try { return Activator.CreateInstance(targetType); } catch { } } return null; }
public XElement SerializeRoot(object obj, Type rootType, XName name, XSerializerNamespaceCollection namespaces, SerializationScope globalScope) { Debug.Assert(rootType.IsInstanceOfType(obj)); Debug.Assert(namespaces != null); var root = SerializeXElement(obj, rootType, name, globalScope); //导入命名空间。 foreach (var ns in namespaces) root.SetAttributeValue(XNamespace.Xmlns + ns.Prefix, ns.Uri); //处理导入的类型。 var nsCounter = 0; foreach (var descendant in root.Descendants()) { var actualTypeName = descendant.Annotation<XName>(); if (actualTypeName != null) { if (actualTypeName.Namespace == descendant.GetDefaultNamespace()) { descendant.SetAttributeValue(SerializationHelper.Xsi + "type", actualTypeName.LocalName); } else { var prefix = descendant.GetPrefixOfNamespace(actualTypeName.Namespace); if (prefix == null) { nsCounter++; prefix = "nss" + nsCounter; descendant.SetAttributeValue(XNamespace.Xmlns + prefix, actualTypeName.NamespaceName); } descendant.SetAttributeValue(SerializationHelper.Xsi + "type", prefix + ":" + actualTypeName.LocalName); } descendant.RemoveAnnotations<XName>(); } } return root; }
// Token: 0x060000B1 RID: 177 RVA: 0x00004584 File Offset: 0x00003584 public virtual object Clone() { ReadOnlyCollection readOnlyCollection = (ReadOnlyCollection)base.MemberwiseClone(); ArrayList arrayList = new ArrayList(this.m_array.Length); System.Type type = null; for (int i = 0; i < this.m_array.Length; i++) { object value = this.m_array.GetValue(i); if (type == null) { type = value.GetType(); } else if (type != typeof(object)) { while (!type.IsInstanceOfType(value)) { type = type.BaseType; } } arrayList.Add(Convert.Clone(value)); } readOnlyCollection.Array = arrayList.ToArray(type); return(readOnlyCollection); }
public static object ChangeType(object value, Type conversionType) { if (value == null) { return null; } Type valueType = value.GetType(); bool valueIsJava = valueType.IsSubclassOf(_javaObjectType) || valueType == _javaObjectType; bool expectedIsJava = conversionType.IsSubclassOf(_javaObjectType) || conversionType == _javaObjectType; if (expectedIsJava) { if (valueIsJava) { return value; } return value.WrapIntoJava(); } if (valueIsJava) { object underlyingObject = (value as Object).ToManaged(); if (underlyingObject != null) { value = underlyingObject; } } if (conversionType.IsInstanceOfType(value)) { return value; } return Convert.ChangeType(value, conversionType); }
public int Add(int jobId, object data, Type dataType) { if (!dataType.IsInstanceOfType(data)) throw new Exception("Incompatible type against data"); return AddInternal(jobId, data, dataType, DataEntryType.Direct); }
static bool KeepOriginal(object arg, Type targetType) { return arg == null || targetType == typeof(object) || targetType.IsInstanceOfType(arg) || (targetType.IsEnum && arg.GetType() == typeof(int)); }
/// <summary> /// Creates a deep copy of the collection. /// </summary> public virtual object Clone() { ReadOnlyCollection clone = (ReadOnlyCollection)this.MemberwiseClone(); ArrayList array = new ArrayList(m_array.Length); // clone the elements and determine the element type. System.Type elementType = null; for (int ii = 0; ii < m_array.Length; ii++) { object element = m_array.GetValue(ii); if (elementType == null) { elementType = element.GetType(); } else if (elementType != typeof(object)) { while (!elementType.IsInstanceOfType(element)) { elementType = elementType.BaseType; } } array.Add(Opc.Convert.Clone(element)); } // convert array list to an array. clone.Array = array.ToArray(elementType); return(clone); }
public static bool ChangeToCompatibleType(string value, Type destinationType, out object result) { if (string.IsNullOrEmpty(value)) { result = null; return false; } if (destinationType.IsInstanceOfType(value)) { result = value; return true; } try { result = TypeDescriptor.GetConverter(destinationType).ConvertFrom(value); return true; } catch { result = null; return false; } }
/// <summary> /// Converts a value to the specified type using either .NET or COM conversion rules. /// </summary> private static object ChangeType(object source, System.Type type, bool supportsCOM) { if (source == null || type == null) { return(source); } // check for an invalid req type. if (type == Opc.Type.ILLEGAL_TYPE) { throw new ResultIDException(ResultID.Da.E_BADTYPE); } // check for no conversion. if (type.IsInstanceOfType(source)) { return(Opc.Convert.Clone(source)); } // convert the data. if (supportsCOM) { return(ChangeTypeForCOM(source, type)); } else { return(ChangeType(source, type)); } }
public virtual object GetService (WorkspaceItem item, Type type) { if (type.IsInstanceOfType (this)) return this; else return GetNext (item).GetService (item, type); }
private static object ConvertType(object value, System.Type type) { if (value == null) { return(null); } if (type.IsInstanceOfType(value)) { return(value); } type = type.UnwrapIfNullable(); if (type.IsEnum) { return(Enum.ToObject(type, value)); } if (type.IsPrimitive) { return(Convert.ChangeType(value, type)); } throw new ArgumentException(string.Format("Cannot convert '{0}' to {1}", value, type)); }
public object GetValue(Type targetType) { var stringValue = _underlyingValue as string; if (_underlyingValue == null) { if (targetType.IsValueType && !(targetType.IsGenericType && targetType.GetGenericTypeDefinition() == typeof(Nullable<>))) { var valueAsString = string.IsNullOrEmpty(stringValue) ? "<null>" : string.Format("\"{0}\"", _underlyingValue); throw new ArgumentException(string.Format("Cannot convert {0} to {1} (Column: '{2}', Row: {3})", valueAsString, targetType.Name, Header, Row)); } return null; } ValueHasBeenUsed = true; if (targetType.IsInstanceOfType(_underlyingValue)) return _underlyingValue; if (targetType.IsEnum && _underlyingValue is string) return Enum.Parse(targetType, (string)_underlyingValue); if (targetType == typeof(DateTime)) return DateTime.Parse(stringValue); try { return Convert.ChangeType(_underlyingValue, targetType); } catch (InvalidCastException ex) { throw new UnassignableExampleException(string.Format( "{0} cannot be assigned to {1} (Column: '{2}', Row: {3})", _underlyingValue == null ? "<null>" : _underlyingValue.ToString(), targetType.Name, Header, Row), ex, this); } }
public IService GetService( Type serviceType ) { IService theService = null; if (serviceIndex.ContainsKey(serviceType)) theService = (IService)serviceIndex[serviceType]; else foreach( IService service in services ) { // TODO: Does this work on Mono? if( serviceType.IsInstanceOfType( service ) ) { serviceIndex[serviceType] = service; theService = service; break; } } if (theService == null) log.Error(string.Format("Requested service {0} was not found", serviceType.FullName)); else log.Debug(string.Format("Request for service {0} satisfied by {1}", serviceType.Name, theService.GetType().Name)); return theService; }
public virtual object GetService(Type serviceType) { if (serviceType.IsInstanceOfType(this)) return this; else return null; }
public object GetCustomAttribute(object obj, Type type, bool inherit) { foreach (object att in GetCustomAttributes (obj, type, inherit)) if (type.IsInstanceOfType (att)) return att; return null; }
public void ShouldResolverIConfigurationProvider(Type type) { _container .Resolve(type) .Should() .NotBeNull().And.Match(b => type.IsInstanceOfType(b)); }
public static bool TryCast(Type contractType, object value, out object result) { if (value == null) { result = null; return true; } if (contractType.IsInstanceOfType(value)) { result = value; return true; } // We couldn't cast see if a delegate works for us. if (typeof(Delegate).IsAssignableFrom(contractType)) { ExportedDelegate exportedDelegate = value as ExportedDelegate; if (exportedDelegate != null) { result = exportedDelegate.CreateDelegate(contractType); return (result != null); } } result = null; return false; }
public static object GetObjectAs(Moniker key, Type type) { object o = GetObject(key); if (type.IsInstanceOfType(o)) return o; Marshal.ReleaseComObject(o); return null; }
public void AddExtendedBrowsingHandlers(Hashtable handlers) { object targetObject = this.TargetObject; if (targetObject != null) { for (int i = 0; i < extendedInterfaces.Length; i++) { System.Type type = extendedInterfaces[i]; if (type.IsInstanceOfType(targetObject)) { Com2ExtendedBrowsingHandler handler = (Com2ExtendedBrowsingHandler)handlers[type]; if (handler == null) { handler = (Com2ExtendedBrowsingHandler)Activator.CreateInstance(extendedInterfaceHandlerTypes[i]); handlers[type] = handler; } if (!type.IsAssignableFrom(handler.Interface)) { throw new ArgumentException(System.Windows.Forms.SR.GetString("COM2BadHandlerType", new object[] { type.Name, handler.Interface.Name })); } handler.SetupPropertyHandlers(this.props); } } } }
protected internal virtual object GetInheritedValue(RadProperty property) { if (this.GetBitState(1L) || this.GetBitState(2L)) { return(RadProperty.UnsetValue); } int globalIndex = property.GlobalIndex; System.Type ownerType = property.OwnerType; object obj = RadProperty.UnsetValue; for (RadObject inheritanceParent = this.InheritanceParent; inheritanceParent != null; inheritanceParent = inheritanceParent.InheritanceParent) { if (ownerType.IsInstanceOfType((object)inheritanceParent)) { RadPropertyValue entry = inheritanceParent.propertyValues.GetEntry(property, false); if (entry != null) { obj = entry.GetCurrentValue(true); break; } } } return(obj); }
protected override bool TryConvertClass(System.Type type, IReferenceMap referenceMap, object value, out object result) { if (value == null || (value as JToken)?.Type == JTokenType.Null) { result = null; return(true); } if (value is JObject jsonValue && jsonValue.ContainsKey("$jsii.byref")) { ByRefValue byRefValue = jsonValue.ToObject <ByRefValue>(); result = referenceMap.GetOrCreateNativeReference(byRefValue); if (!type.IsInstanceOfType(result) && result is IConvertible) { result = Convert.ChangeType(result, type); } return(result != null); } result = null; return(false); }
//IAdaptable public virtual IAdaptable GetAdapter(Type adapter) { #if UNITTEST return adapter.IsInstanceOfType(this) ? this : null; //UnitTestではPoderosaの起動にならないケースもある #else return ProtocolsPlugin.Instance.PoderosaWorld.AdapterManager.GetAdapter(this, adapter); #endif }
public virtual object Clone() { ReadOnlyCollection onlys = (ReadOnlyCollection)base.MemberwiseClone(); ArrayList list = new ArrayList(this.m_array.Length); System.Type baseType = null; for (int i = 0; i < this.m_array.Length; i++) { object o = this.m_array.GetValue(i); if (baseType == null) { baseType = o.GetType(); } else if (baseType != typeof(object)) { while (!baseType.IsInstanceOfType(o)) { baseType = baseType.BaseType; } } list.Add(Opc.Convert.Clone(o)); } onlys.Array = list.ToArray(baseType); return(onlys); }
public virtual object GetService (IBuildTarget item, Type type) { if (type.IsInstanceOfType (this)) return this; else return GetNext (item).GetService (item, type); }
//Methods public virtual void Add(string key, Element value) { if (!mModifiable) { throw new CollectionNotModifiableException("This collection is not modifiable."); } if (value == null) { throw new ArgumentNullException("value", "Element parameter cannot be null reference."); } if (key == null) { throw new ArgumentNullException("key", "Key may not be null."); } if (key == "") { throw new ArgumentException("Key may not be null string.", "key"); } if (!mBaseType.IsInstanceOfType(value) && !value.GetType().IsSubclassOf(mBaseType)) { throw new ArgumentException("Items added to this collection must be of or inherit from type '" + mBaseType.ToString()); } //Key can be reset by removing and then readding to collection value.SetKey(key); Dictionary.Add(key, value); //Zordering now done outside the collection //Since multiple collections can contain the same reference eg layer OnInsert(key, value); }
/// <inheritdoc /> public IFieldInterceptor InjectInterceptor(object entity, ISessionImplementor session) { if (!EnhancedForLazyLoading) { throw new NotInstrumentedException($"Entity class [{_entityType}] is not enhanced for lazy loading"); } if (!(entity is IFieldInterceptorAccessor fieldInterceptorAccessor)) { return(null); // Can happen when a saved entity is refreshed within the same session NH2860 } if (!_entityType.IsInstanceOfType(entity)) { throw new ArgumentException( $"Passed entity instance [{entity}] is not of expected type [{EntityName}]"); } var fieldInterceptorImpl = new DefaultFieldInterceptor( session, LazyPropertiesMetadata.HasLazyProperties ? new HashSet <string>(LazyPropertiesMetadata.LazyPropertyNames) : null, UnwrapProxyPropertiesMetadata.UnwrapProxyPropertyNames, EntityName, _entityType); fieldInterceptorAccessor.FieldInterceptor = fieldInterceptorImpl; return(fieldInterceptorImpl); }
internal static void RenderNullModelMessage(HtmlTextWriter writer, string viewName, string dataSource, Type modelType, object model, Exception exception) { writer.AddAttribute("style", "border: 1px dashed red; padding: .5em;"); writer.RenderBeginTag("div"); writer.Write("<p><strong>Hidden Rendering:</strong> {0}</p>", viewName); writer.Write("<p>Rendering was hidden because the content data source provided did not have the expected data structure.</p>"); if (!string.IsNullOrWhiteSpace(dataSource)) writer.Write("<p>The rendering's data source value, <span style=\"font-family: monospace\">{0}</span>, may point to an invalid Sitecore item or an item of the wrong template type. Use the <em>Set Associated Content</em> button to point the data source to a valid item.</p>", dataSource); if (model != null && !modelType.IsInstanceOfType(model)) { writer.Write("<p>The model received was of type <span style=\"font-family: monospace\">{0}</span> which cannot be converted to the expected model type <span style=\"font-family: monospace\">{1}</span></p>", model.GetType().Name, modelType.Name); } else if (model != null) { writer.Write("<p>The model for <span style=\"font-family: monospace\">{0}</span> was a <strong>valid</strong> model type. <strong>This means a partial view included on the current rendering had an invalid model type.</strong> Unfortunately, we can't be sure which partial caused the problem.</p>", Path.GetFileName(viewName)); } if (model == null) { writer.Write("<p>The received model was null, and we cannot render the view with a null model (expected type: <span style=\"font-family: monospace\">{0}</span></p>", modelType.Name); } if (DebugUtility.IsDynamicDebugEnabled) { writer.Write("<p><span style=\"font-family: monospace; font-weight: bold;\">{0}</span></p><pre>{1}</pre>", exception.Message, exception.StackTrace); } writer.Write("<p><em>This message is only displayed in preview or edit mode, and will not appear to end users.</em></p>"); writer.RenderEndTag(); // div }
public object Intercept(object instance, Type typeToIntercept, IInterceptionHandler handler) { if (instance == null) { throw (new ArgumentNullException("instance")); } if (typeToIntercept == null) { throw (new ArgumentNullException("typeToIntercept")); } if (handler == null) { throw (new ArgumentNullException("handler")); } if (this.CanIntercept(instance) == false) { throw (new ArgumentException("instance")); } if (typeToIntercept.IsInstanceOfType(instance) == false) { throw (new ArgumentException("typeToIntercept")); } var proxy = new TransparentProxy(this, instance, typeToIntercept, handler); return (proxy.GetTransparentProxy()); }
public object DeserializeRoot(XElement e, object existingObject, Type rootType, SerializationScope globalScope) { var obj = DeserializeXElement(e, existingObject, rootType, globalScope); if (!rootType.IsInstanceOfType(obj)) throw new InvalidOperationException("Invalid root element : " + e.Name); return obj; }
static ByteString EncodeObject (object value, Type type, MemoryStream buffer, CodedOutputStream stream) { buffer.SetLength (0); if (value != null && !type.IsInstanceOfType (value)) throw new ArgumentException ("Value of type " + value.GetType () + " cannot be encoded to type " + type); if (value == null && !type.IsSubclassOf (typeof(RemoteObject)) && !IsACollectionType (type)) throw new ArgumentException ("null cannot be encoded to type " + type); if (value == null) stream.WriteUInt64 (0); else if (value is Enum) stream.WriteInt32 ((int)value); else { switch (Type.GetTypeCode (type)) { case TypeCode.Int32: stream.WriteInt32 ((int)value); break; case TypeCode.Int64: stream.WriteInt64 ((long)value); break; case TypeCode.UInt32: stream.WriteUInt32 ((uint)value); break; case TypeCode.UInt64: stream.WriteUInt64 ((ulong)value); break; case TypeCode.Single: stream.WriteFloat ((float)value); break; case TypeCode.Double: stream.WriteDouble ((double)value); break; case TypeCode.Boolean: stream.WriteBool ((bool)value); break; case TypeCode.String: stream.WriteString ((string)value); break; default: if (type.Equals (typeof(byte[]))) stream.WriteBytes (ByteString.CopyFrom ((byte[])value)); else if (IsAClassType (type)) stream.WriteUInt64 (((RemoteObject)value).id); else if (IsAMessageType (type)) ((IMessage)value).WriteTo (buffer); else if (IsAListType (type)) WriteList (value, type, buffer); else if (IsADictionaryType (type)) WriteDictionary (value, type, buffer); else if (IsASetType (type)) WriteSet (value, type, buffer); else if (IsATupleType (type)) WriteTuple (value, type, buffer); else throw new ArgumentException (type + " is not a serializable type"); break; } } stream.Flush (); return ByteString.CopyFrom (buffer.GetBuffer (), 0, (int)buffer.Length); }
/// <summary> /// Convert the specified value to destinationType. /// </summary> /// <param name="value"></param> /// <param name="destinationType"></param> /// <param name="paramName">Name used for reporting</param> /// <returns></returns> public static object BuildObjectValue(object value, Type destinationType, string paramName) { if ((value != null) && !destinationType.IsInstanceOfType(value)) { Type elementType = destinationType; bool isNullableType = false; if (destinationType.IsGenericType && (destinationType.GetGenericTypeDefinition() == typeof(Nullable<>))) { elementType = destinationType.GetGenericArguments()[0]; isNullableType = true; } else if (destinationType.IsByRef) { elementType = destinationType.GetElementType(); } value = ConvertType(value, elementType); if (isNullableType) { Type type = value.GetType(); if (elementType != type) { throw new InvalidOperationException(String.Format("Can't convert type from {0} to Nullable<{1}>", destinationType.GetGenericArguments()[0].FullName)); } } } return value; }
// Token: 0x060002A7 RID: 679 RVA: 0x00007617 File Offset: 0x00006617 protected virtual void ValidateValue(object element, System.Type type) { if (element != null && !type.IsInstanceOfType(element)) { throw new ArgumentException(string.Format("A {1} with type '{0}' cannot be added to the dictionary.", element.GetType(), "value")); } }
/// <summary> /// 遞迴尋找符合條件的控制項。 /// </summary> /// <param name="Parent">父控制項。</param> /// <param name="Type">欲尋找的控制項型別。</param> /// <param name="PropertyName">比對的屬性名稱。</param> /// <param name="PropertyValue">比對的屬性值。</param> public static object FindControlEx(System.Web.UI.Control Parent, System.Type Type, string PropertyName, object PropertyValue) { //System.Web.UI.Control oControl = default(System.Web.UI.Control); object oFindControl = null; object oValue = null; foreach (Control oControl in Parent.Controls) { if (Type.IsInstanceOfType(oControl)) { //取得屬性值 oValue = GetPropertyValue(oControl, PropertyName); if (oValue.Equals(PropertyValue)) { //型別及屬性值皆符合則回傳此控制項 return(oControl); } } else { if (oControl.Controls.Count > 0) { //遞迴往下尋找符合條件的控制項 oFindControl = FindControlEx(oControl, Type, PropertyName, PropertyValue); if (oFindControl != null) { return(oFindControl); } } } } return(null); }
private static object ConvertSimpleType(CultureInfo culture, object value, Type destinationType) { if (value == null || destinationType.IsInstanceOfType(value)) { return value; } // if this is a user-input value but the user didn't type anything, return no value string valueAsString = value as string; if (valueAsString != null && valueAsString.Trim().Length == 0) { return null; } TypeConverter converter = TypeDescriptor.GetConverter(destinationType); bool canConvertFrom = converter.CanConvertFrom(value.GetType()); if (!canConvertFrom) { converter = TypeDescriptor.GetConverter(value.GetType()); } if (!(canConvertFrom || converter.CanConvertTo(destinationType))) { string message = String.Format(CultureInfo.CurrentCulture, MvcResources.ValueProviderResult_NoConverterExists, value.GetType().FullName, destinationType.FullName); throw new InvalidOperationException(message); } try { object convertedValue = (canConvertFrom) ? converter.ConvertFrom(null /* context */, culture, value) : converter.ConvertTo(null /* context */, culture, value, destinationType); return convertedValue; } catch (Exception ex) { string message = String.Format(CultureInfo.CurrentCulture, MvcResources.ValueProviderResult_ConversionThrew, value.GetType().FullName, destinationType.FullName); throw new InvalidOperationException(message, ex); } }
public static void Type(Value val, System.Type requiredType, string desc = null) { if (!requiredType.IsInstanceOfType(val)) { throw new TypeException(string.Format("got a {0} where a {1} was required{2}", val.GetType(), requiredType, desc == null ? null : " (" + desc + ")")); } }
private IEnumerable <InvalidValue> GetInvalidValues(object entity, HashSet <object> circularityState, ICollection <object> activeTags) { if (entity == null || circularityState.Contains(entity)) { return(EmptyInvalidValueArray); //Avoid circularity } circularityState.Add(entity); if (!entityType.IsInstanceOfType(entity)) { throw new ArgumentException("not an instance of: " + entity.GetType()); } return (EntityInvalidValues(entity, activeTags) .Concat(MembersInvalidValues(entity, null, activeTags)) .Concat(GetChildrenInvalidValues(entity, circularityState, activeTags))); }
private static void checkCorrectType(ICollection coll, Type t) { foreach (object o in coll) { if (!t.IsInstanceOfType(o)) throw new InvalidCastException("Can't cast object to type: " + t.FullName); } }
protected override void OnValueChanging(ValueChangedEventArgs e) { if (e.NewValue != null && !_attributeType.IsInstanceOfType(e.NewValue)) { throw new ArgumentException($"Value {e.NewValue} is not of expected type {_attributeType.Name}."); } base.OnValueChanging(e); }
// -- Many thanks to Bea Stollnitz, on whose blog I found the original C# version of below in a drag-drop helper class... public static FrameworkElement FindVisualAncestor(System.Type ancestorType, System.Windows.Media.Visual visual) { while ((visual != null && !ancestorType.IsInstanceOfType(visual))) { visual = (System.Windows.Media.Visual)System.Windows.Media.VisualTreeHelper.GetParent(visual); } return((FrameworkElement)visual); }
public static FrameworkElement FindAncestor(Type ancestorType, Visual visual) { while (visual != null && !ancestorType.IsInstanceOfType(visual)) { visual = (Visual)VisualTreeHelper.GetParent(visual); } return visual as FrameworkElement; }
public Instruction Ancestor(System.Type type) { Instruction ins = m_parent; while (ins != null && !(type.IsInstanceOfType(ins))) { ins = ins.Parent; } return(ins); // may be null! }
//================================================================================ #endregion #region Implementation - System.Collections.IList<ItemBase> //================================================================================ void IList <T> .Insert(int index, T item) { // Validate if (_readOnly || _fixedSize) { throw new NotSupportedException(); } if (_itemType != null && !_itemType.IsInstanceOfType(item)) { throw new ArgumentException(); } if (!(item is IItem)) { throw new ArgumentException(); } // Insert this.BaseInsert(index, (T)item); }
/// <summary> /// Throws an exception if the value is not valid for the dictionary. /// </summary> protected virtual void ValidateValue(object element, System.Type type) { if (element != null) { if (!type.IsInstanceOfType(element)) { throw new ArgumentException(String.Format(INVALID_TYPE, element.GetType(), "value")); } } }
internal static object QueryStateObject(System.Type t, int controlID) { object o = GUIStateObjects.s_StateCache[controlID]; if (t.IsInstanceOfType(o)) { return(o); } return((object)null); }
//Adds an TableItem to the list public virtual int Add(TableItem value) { if (value == null) { throw new ArgumentNullException("TableItem parameter cannot be null reference.", "value"); } if (!mBaseType.IsInstanceOfType(value) && !value.GetType().IsSubclassOf(mBaseType)) { throw new ArgumentException("Items added to this collection must be of or inherit from type '" + mBaseType.ToString()); } int index = List.Add(value); if (!mSuspendEvents && InsertItem != null) { InsertItem(this, new TableItemsEventArgs((TableItem)value)); } return(index); }
public bool IsInstance(object obj) { try { return(entityType.IsInstanceOfType(obj)); } catch (Exception e) { throw new HibernateException("could not get handle to entity-name as interface : " + e); } }
/// <summary> /// Throws an exception if the element is not valid for the collection. /// </summary> protected virtual void ValidateElement(object element) { if (element == null) { throw new ArgumentException(String.Format(INVALID_VALUE, element)); } if (!_elementType.IsInstanceOfType(element)) { throw new ArgumentException(String.Format(INVALID_TYPE, element.GetType())); } }
public static Component AddIfMissing(this GameObject targetObject, System.Type interfaceType, System.Type concreteType) { foreach (Component c in targetObject.GetComponents <Component>()) { if (interfaceType.IsInstanceOfType(c)) { return(c); } } return(targetObject.AddComponent(concreteType) as Component); }
public static bool InterfaceFilterCallback(System.Type type, object criteria) { foreach (System.Type interfaceName in (System.Type[])criteria) { if (type.IsInstanceOfType(interfaceName)) { return(true); } } return(false); }