public override bool OnSave(object entity, object id, object[] state, string[] propertyNames, IType[] types) { //Set CreationTime for new entity //if (entity is IUpdater) //{ // for (var i = 0; i < propertyNames.Length; i++) // { // if (propertyNames[i] == "CreationTime") // { // state[i] = (entity as IUpdater).UpdatedTime = Clock.Now; // } // } //} ////Set CreatorUserId for new entity //if (entity is ICreationAudited) //{ // for (var i = 0; i < propertyNames.Length; i++) // { // if (propertyNames[i] == "CreatorUserId") // { // state[i] = (entity as ICreationAudited).CreatorUserId = _abpSession.Value.UserId; // } // } //} // EntityChangeEventHelper.TriggerEntityCreatingEvent(entity); // EntityChangeEventHelper.TriggerEntityCreatedEventOnUowCompleted(entity); return base.OnSave(entity, id, state, propertyNames, types); }
public HibernateProperty(string name, object val, IType type, object owner) { Name = name; this.val = val; this.owner = owner; this.type = new HibernateType(type); }
public IType CheckApp(IType type1, IKind kind, IType type2) { /* (TApp (TCPoly kind2) (TAbs unique type6)) = type1; return CheckPolymorphicTypeApp(kind2, kind, unique, type6, type2); */ if (type1 is TApp) { IType type4 = ((TApp)type1).Function; IType type5 = ((TApp)type1).Argument; if (type4 is TCPoly) { IKind kind2 = ((TCPoly)type4).Kind; if (type5 is TAbs) { Unique unique = ((TAbs)type5).Parameter; IType type6 = ((TAbs)type5).Body; return CheckPolymorphicTypeApp( kind2, kind, unique, type6, type2 ); } } } throw new ArgumentException( string.Format( "{0} doesn't have a polymorphic type", mValueExpr.Show() ) ); }
/// <summary> /// Gets whether the specified type is a nullable type. /// </summary> public static bool IsNullable(IType type) { if (type == null) throw new ArgumentNullException("type"); ParameterizedType pt = type as ParameterizedType; return pt != null && pt.TypeArguments.Count == 1 && pt.FullName == "System.Nullable"; }
public GenerateNamespaceImport GetResult (IUnresolvedFile unit, IType type, MonoDevelop.Ide.Gui.Document doc) { GenerateNamespaceImport result; if (cache.TryGetValue (type.Namespace, out result)) return result; result = new GenerateNamespaceImport (); cache[type.Namespace] = result; TextEditorData data = doc.Editor; result.InsertNamespace = false; var loc = new TextLocation (data.Caret.Line, data.Caret.Column); foreach (var ns in RefactoringOptions.GetUsedNamespaces (doc, loc)) { if (type.Namespace == ns) { result.GenerateUsing = false; return result; } } result.GenerateUsing = true; string name = type.Name; foreach (string ns in RefactoringOptions.GetUsedNamespaces (doc, loc)) { if (doc.Compilation.MainAssembly.GetTypeDefinition (ns, name, type.TypeParameterCount) != null) { result.GenerateUsing = false; result.InsertNamespace = true; return result; } } return result; }
/// <summary> /// </summary> /// <param name="llvmWriter"> /// </param> /// <param name="opCode"> /// </param> /// <param name="elementType"> /// </param> /// <param name="length"> /// </param> public static FullyDefinedReference WriteStringAllocationSize( this LlvmWriter llvmWriter, OpCodePart opCode, IType stringType, IType charType) { Debug.Assert(stringType.IsString, "This is for string only"); var writer = llvmWriter.Output; writer.WriteLine("; Calculate String allocation size"); object[] code; IList<object> tokenResolutions; IList<IType> locals; IList<IParameter> parameters; GetCalculationPartOfStringAllocationSizeMethodBody( llvmWriter, stringType, charType, out code, out tokenResolutions, out locals, out parameters); var constructedMethod = MethodBodyBank.GetMethodDecorator(null, code, tokenResolutions, locals, parameters); // actual write var opCodes = llvmWriter.WriteCustomMethodPart(constructedMethod, null); return opCodes.Last().Result; }
public bool Equals(IType type) { if (type == null) throw new ArgumentNullException("type"); if (!(type is DotNetType)) throw new ArgumentException("type"); if (_type == null) return false; return this._type.Equals(((DotNetType)type).Type); }
/// <summary> /// Validates and constructs generic entities out of an ambiguous generic definition entity. /// </summary> private IEntity ConstructAmbiguousEntity(Node constructionNode, Ambiguous ambiguousDefinition, IType[] typeArguments) { var checker = new GenericConstructionChecker(typeArguments, constructionNode); var matches = new List<IEntity>(ambiguousDefinition.Entities); bool reportErrors = false; foreach (Predicate<IEntity> check in checker.Checks) { matches = matches.Collect(check); if (matches.Count == 0) { Errors.Add(checker.Errors[0]); // only report first error, assuming the rest are superfluous return TypeSystemServices.ErrorEntity; } if (reportErrors) checker.ReportErrors(Errors); checker.DiscardErrors(); // We only want full error reporting once we get down to a single candidate if (matches.Count == 1) reportErrors = true; } IEntity[] constructedMatches = Array.ConvertAll<IEntity, IEntity>(matches.ToArray(), def => MakeGenericEntity(def, typeArguments)); return Entities.EntityFromList(constructedMatches); }
public BoundBinaryExpression(BoundExpression left, BoundExpression right, BinaryOperators @operator, BinaryExpressionSyntax binaryExpressionSyntax, IType type) : base(binaryExpressionSyntax, type) { Left = left; Right = right; Operator = @operator; }
public QueryParameters(IType[] positionalParameterTypes, object[] postionalParameterValues, object optionalObject, string optionalEntityName, object optionalObjectId) : this(positionalParameterTypes, postionalParameterValues) { OptionalObject = optionalObject; OptionalId = optionalObjectId; OptionalEntityName = optionalEntityName; }
protected override bool IsAvailableForType(IType type) { var context = Provider.SelectedElement; Debug.Assert(context != null); if ((type.IsCollectionLike() || type.IsGenericArray(context)) && !type.IsGenericIEnumerable() && !type.IsArray()) { var elementType = CollectionTypeUtil.ElementTypeByCollectionType(type, context); if (elementType != null) { if (elementType.Classify == TypeClassification.REFERENCE_TYPE) { isDictionary = false; return true; } var declaredType = type as IDeclaredType; if (declaredType != null && (declaredType.GetKeyValueTypesForGenericDictionary() ?? Enumerable.Empty<JetBrains.Util.Pair<IType, IType>>()).Any( pair => pair.Second.Classify == TypeClassification.REFERENCE_TYPE)) { isDictionary = true; return true; } } } return false; }
private JsBlockStatement MakeIteratorBody(IteratorStateMachine sm, bool returnsIEnumerable, IType yieldType, string yieldResultVariable, IList<string> methodParameterNames) { var body = new List<JsStatement>(); body.Add(JsStatement.Var(new[] { JsStatement.Declaration(yieldResultVariable, null) }.Concat(sm.Variables))); body.AddRange(sm.FinallyHandlers.Select(h => JsStatement.Var(h.Item1, h.Item2))); body.Add(JsStatement.Return(_runtimeLibrary.MakeEnumerator(yieldType, JsExpression.FunctionDefinition(new string[0], sm.MainBlock), JsExpression.FunctionDefinition(new string[0], JsStatement.Return(JsExpression.Identifier(yieldResultVariable))), sm.Disposer != null ? JsExpression.FunctionDefinition(new string[0], sm.Disposer) : null, this))); if (returnsIEnumerable) { body = new List<JsStatement> { JsStatement.Return(_runtimeLibrary.MakeEnumerable( yieldType, JsExpression.FunctionDefinition(new string[0], JsStatement.Return( JsExpression.Invocation( JsExpression.Member( JsExpression.FunctionDefinition(methodParameterNames, JsStatement.Block(body)), "call"), new JsExpression[] { JsExpression.This }.Concat(methodParameterNames.Select(JsExpression.Identifier)) ) ) ), this )) }; } return JsStatement.Block(body); }
public LIType BuscarPorHierarquiaENivel(IType iType, int idHierarquia, int idSubNivel, int idCampanha) { try { Cmd = DataBaseGeneric.CreateCommand(BaseType); Cmd.Connection = Cn; Cmd.CommandType = CommandType.StoredProcedure; Cmd.CommandText = "Sp_Ambev_Lista_Nivel_Hierarquia_dsPessoa"; DbParameter paran = Cmd.CreateParameter(); paran.ParameterName = "@nivel"; paran.Value = idSubNivel; Cmd.Parameters.Add(paran); DbParameter paran1 = Cmd.CreateParameter(); paran1.ParameterName = "@idHierarquiaPai"; paran1.Value = idHierarquia; Cmd.Parameters.Add(paran1); DbParameter paran2 = Cmd.CreateParameter(); paran2.ParameterName = "@idcampanha"; paran2.Value = idCampanha; Cmd.Parameters.Add(paran2); return MakeListToGet(iType); } catch (Exception ex) { throw ex; } finally { Cn.Close(); Cn.Dispose(); } }
public ICompletionData CreateEventCreationCompletionData(string varName, IType delegateType, IEvent evt, string parameterDefinition, IUnresolvedMember currentMember, IUnresolvedTypeDefinition currentType) { return new CompletionData(varName); }
public bool OnFlushDirty(object entity, object id, object[] currentState, object[] previousState, string[] propertyNames, IType[] types) { logger.Debug("throwing validation exception"); throw new ApplicationException("imaginary validation error"); }
public void Save(IType iType, int idPessoa, int idCargo) { try { Cmd = DataBaseGeneric.CreateCommand(BaseType); Cmd.Connection = Cn; Cmd.CommandType = CommandType.StoredProcedure; Cmd.CommandText = "sp_SaveCargoEstrutura"; DbParameter paran1 = Cmd.CreateParameter(); paran1.ParameterName = "@idCargo"; paran1.Value = idCargo; Cmd.Parameters.Add(paran1); DbParameter paran2 = Cmd.CreateParameter(); paran2.ParameterName = "@idPessoa"; paran2.Value = idPessoa; Cmd.Parameters.Add(paran2); OpenConnectionTrans(iType); Cmd.ExecuteNonQuery(); } catch (Exception ex) { throw ex; } finally { Cn.Close(); Cn.Dispose(); } }
/// <summary> /// </summary> /// <param name="type"> /// </param> /// <param name="typeResolver"> /// </param> public SynthesizedSingleDimArrayIListGetEnumeratorMethod(IType arrayType, ITypeResolver typeResolver) : base("GetEnumerator", arrayType, typeResolver.System.System_Collections_Generic_IEnumerator_T.Construct(arrayType.GetElementType())) { var codeList = new IlCodeBuilder(); codeList.LoadArgument(0); codeList.Add(Code.Newobj, 1); codeList.Add(Code.Newobj, 2); codeList.Add(Code.Ret); var locals = new List<IType>(); this._methodBody = new SynthesizedMethodBodyDecorator( null, locals, codeList.GetCode()); this._parameters = new List<IParameter>(); this._tokenResolutions = new List<object>(); var arraySegmentType = typeResolver.System.System_ArraySegment_T1.Construct(arrayType.GetElementType()); this._tokenResolutions.Add( IlReader.Constructors(arraySegmentType, typeResolver).First(c => c.GetParameters().Count() == 1)); this._tokenResolutions.Add( IlReader.Constructors(arraySegmentType.GetNestedTypes().First(), typeResolver).First(c => c.GetParameters().Count() == 1)); }
private static void RegisterType(System.Type systemType, IType nhibernateType, IEnumerable<string> aliases) { var typeAliases = new List<string>(aliases); typeAliases.AddRange(GetClrTypeAliases(systemType)); RegisterType(nhibernateType, typeAliases); }
public BaseTypeWalker(IType type, ComponentCache componentCache = null) : this(componentCache) { Contract.Requires<ArgumentNullException>(type != null); this.type = type.TypeDefinition; }
public override void Dispose() { _asyncResultType = null; _asyncResultTypeAsyncDelegateGetter = null; _adaptors.Clear(); base.Dispose(); }
public void AddType (IType type, string shortType) { if (type == null || string.IsNullOrEmpty (shortType) || usedTypes.Contains (shortType)) return; usedTypes.Add (shortType); result.Add (Factory.CreateTypeCompletionData (type, shortType)); }
public string GetTypeReferenceString (IType type, bool highlight = true) { if (type == null) throw new ArgumentNullException ("type"); if (type.Kind == TypeKind.Null) return "?"; if (type.Kind == TypeKind.Array) { var arrayType = (ArrayType)type; return GetTypeReferenceString (arrayType.ElementType, highlight) + "[" + new string (',', arrayType.Dimensions - 1) + "]"; } if (type.Kind == TypeKind.Pointer) return GetTypeReferenceString (((PointerType)type).ElementType, highlight) + "*"; AstType astType; try { astType = astBuilder.ConvertType (type); } catch (Exception e) { var compilation = GetCompilation (type); if (compilation == null) { Console.WriteLine ("type:"+type.GetType ()); Console.WriteLine ("got exception while conversion:" + e); return "?"; } astType = new TypeSystemAstBuilder (new CSharpResolver (compilation)).ConvertType (type); } if (astType is PrimitiveType) { return Highlight (astType.ToString (formattingOptions), colorStyle.KeywordTypes); } var text = AmbienceService.EscapeText (astType.ToString (formattingOptions)); return highlight ? HighlightSemantically (text, colorStyle.UserTypes) : text; }
public FilterDefinition AddParameter(string name, IType type) { if (string.IsNullOrEmpty(name)) throw new ArgumentException("The name is mandatory", "name"); if (type == null) throw new ArgumentNullException("type"); parameters.Add(name, type); return this; }
public MemberResolveResult(ResolveResult targetResult, IMember member, IType returnType) : base(returnType) { if (member == null) throw new ArgumentNullException("member"); this.targetResult = targetResult; this.member = member; }
public ClassEntry (IType cls, NamespaceEntry namespaceRef) { this.cls = cls; this.namespaceRef = namespaceRef; position = -1; UpdateContent (cls); }
/// <summary> /// Nullify all references to entities that have not yet /// been inserted in the database, where the foreign key /// points toward that entity /// </summary> public void NullifyTransientReferences(object[] values, IType[] types) { for (int i = 0; i < types.Length; i++) { values[i] = NullifyTransientReferences(values[i], types[i]); } }
public static byte[] GetArray(IList<Instruction> instrs, ref int index, out IType type) { for (int i = index; i < instrs.Count - 2; i++) { var newarr = instrs[i++]; if (newarr.OpCode.Code != Code.Newarr) continue; if (instrs[i++].OpCode.Code != Code.Dup) continue; var ldtoken = instrs[i++]; if (ldtoken.OpCode.Code != Code.Ldtoken) continue; var field = ldtoken.Operand as FieldDef; if (field == null || field.InitialValue == null) continue; index = i - 3; type = newarr.Operand as IType; return field.InitialValue; } index = instrs.Count; type = null; return null; }
/// <summary> /// /// </summary> /// <param name="type"></param> /// <param name="parms"></param> /// <param name="d"></param> public void Configure(IType type, IDictionary<string, string> parms, Dialect.Dialect d) { string tableList; string column; string schema; string catalog; if (!parms.TryGetValue("tables", out tableList)) parms.TryGetValue(PersistentIdGeneratorParmsNames.Tables, out tableList); string[] tables = StringHelper.Split(", ", tableList); if (!parms.TryGetValue("column", out column)) parms.TryGetValue(PersistentIdGeneratorParmsNames.PK, out column); returnClass = type.ReturnedClass; parms.TryGetValue(PersistentIdGeneratorParmsNames.Schema, out schema); parms.TryGetValue(PersistentIdGeneratorParmsNames.Catalog, out catalog); StringBuilder buf = new StringBuilder(); for (int i = 0; i < tables.Length; i++) { if (tables.Length > 1) { buf.Append("select ").Append(column).Append(" from "); } buf.Append(Table.Qualify(catalog, schema, tables[i])); if (i < tables.Length - 1) buf.Append(" union "); } if (tables.Length > 1) { buf.Insert(0, "( ").Append(" ) ids_"); column = "ids_." + column; } sql = "select max(" + column + ") from " + buf; }
public FieldProperties(string fieldName, string fieldType) { m_fieldName = fieldName; m_type = Db4oClient.TypeResolver.Resolve(fieldType); m_dataType = m_type.DisplayName; }
public static FlowDocument CreateTooltip(IType type, bool useFullyQualifiedMemberNames = true) { var ambience = AmbienceService.GetCurrentAmbience(); ambience.ConversionFlags = ConversionFlags.StandardConversionFlags | ConversionFlags.ShowDeclaringType; if (useFullyQualifiedMemberNames) ambience.ConversionFlags |= ConversionFlags.UseFullyQualifiedMemberNames; string header; if (type is ITypeDefinition) header = ambience.ConvertEntity((ITypeDefinition)type); else header = ambience.ConvertType(type); ambience.ConversionFlags = ConversionFlags.ShowTypeParameterList; DocumentationUIBuilder b = new DocumentationUIBuilder(ambience); b.AddCodeBlock(header, keepLargeMargin: true); ITypeDefinition entity = type.GetDefinition(); if (entity != null) { var documentation = XmlDocumentationElement.Get(entity); if (documentation != null) { foreach (var child in documentation.Children) { b.AddDocumentationElement(child); } } } return b.CreateFlowDocument(); }
public static bool IsDeclaredAsFieldIn(this IType type, string pattern, bool useRegularExpressions = false) { return(type.GetFieldTypeDependencies(true).Any(dependency => dependency.Target.FullNameMatches(pattern, useRegularExpressions))); }
public static IEnumerable <MethodMember> GetConstructors(this IType type) { return(type.GetMethodMembers().Where(method => method.IsConstructor())); }
public static IEnumerable <MethodMember> GetMethodMembers(this IType type) { return(type.Members.OfType <MethodMember>()); }
public static IEnumerable <PropertyMember> GetPropertyMembers(this IType type) { return(type.Members.OfType <PropertyMember>()); }
public static bool HasDependencies(this IType type, IEnumerable <ITypeDependency> dependencies) { return(dependencies.All(dependency => type.Dependencies.Contains(dependency))); }
public static bool HasDependency(this IType type, ITypeDependency dependency) { return(type.Dependencies.Contains(dependency)); }
public static bool IsAnonymousType(this IType type) { return(type.NameStartsWith("<>f__AnonymousType")); }
public static Attribute GetAttributeOfType(this IType type, Class attributeClass) { return(type.Attributes.Find(attribute => attribute.FullName.Equals(attributeClass.FullName))); }
public static IMember GetMemberWithFullName(this IType type, string fullName) { return(type.Members.WhereFullNameIs(fullName)); }
public static bool ResidesInAssembly(this IType e, string pattern, bool useRegularExpressions = false) { return(e.Assembly.FullNameMatches(pattern, useRegularExpressions)); }
/// <summary> /// Gets whether the lambda body is valid for the given parameter types and return type. /// </summary> /// <returns> /// Produces a conversion with <see cref="Conversion.IsAnonymousFunctionConversion"/>=<c>true</c> if the lambda is valid; /// otherwise returns <see cref="Conversion.None"/>. /// </returns> public abstract Conversion IsValid(IType[] parameterTypes, IType returnType, CSharpConversions conversions);
public static bool HasMemberWithFullName(this IType type, string fullname) { return(type.GetMemberWithFullName(fullname) != null); }
/// <summary> /// Replaces all occurrences of class and method type parameters in the given type /// by normalized type parameters. This allows comparing parameter types from different /// generic methods. /// </summary> public static IType NormalizeAllTypeParameters(IType type) { return(type.AcceptVisitor(normalizeClassTypeParameters).AcceptVisitor(normalizeMethodTypeParameters)); }
public static FieldMember GetFieldMemberWithFullName(this IType type, string fullName) { return(type.GetFieldMembers().WhereFullNameIs(fullName)); }
public VisitorAction Enter( VariableNode node, ISyntaxNode parent, IReadOnlyList <object> path, IReadOnlyList <ISyntaxNode> ancestors) { if (!_declared.Contains(node.Name.Value)) { IType type = _type.Peek(); if (_variables.TryGetValue( node.Name.Value, out VariableDefinitionNode? d)) { if (type.IsNonNullType() && d.Type is INullableTypeNode nullable) { _variables[node.Name.Value] = d.WithType(new NonNullTypeNode(nullable)); } } else { if (type.NamedType() is IComplexOutputType complexType) { Type clrType = complexType.ToRuntimeType(); InputObjectType inputType = _schema.Types.OfType <InputObjectType>() .First(t => t.RuntimeType == clrType); if (inputType is null) { throw CollectVariablesVisitor_NoCompatibleType(node, path); } d = new VariableDefinitionNode ( null, node, type.ToTypeNode(inputType), null, Array.Empty <DirectiveNode>() ); } else { d = new VariableDefinitionNode ( null, node, type.ToTypeNode(), null, Array.Empty <DirectiveNode>() ); } _variables[node.Name.Value] = d; } } return(VisitorAction.Continue); }
protected override bool isCompatibleType(int paramIndex, IType origType, IType newType) { return(true); }
public IType ResolveGenericType(IType contextType) { throw new NotImplementedException(); }
private void CheckMethodDeclaration(IMethodDeclaration methodDeclaration, IAttribute element, IHighlightingConsumer consumer) { if (methodDeclaration == null) { return; } var predefinedType = myPredefinedTypeCache.GetOrCreatePredefinedType(element.GetPsiModule()); var gizmoType = TypeFactory.CreateTypeByCLRName(KnownTypes.GizmoType, predefinedType.Module); var componentType = TypeFactory.CreateTypeByCLRName(KnownTypes.Component, predefinedType.Module); IType derivedType = componentType; var derivedName = "component"; var gizmoName = "gizmoType"; var firstParamCorrect = false; var secondParamCorrect = false; for (var i = 0; i < methodDeclaration.Params.ParameterDeclarations.Count; i++) { var param = methodDeclaration.Params.ParameterDeclarations[i]; if (param.Type.GetTypeElement() ?.IsDescendantOf(componentType.GetTypeElement()) == true) { if (i == 0) { firstParamCorrect = true; } derivedType = param.Type; derivedName = param.DeclaredName; } if (param.Type.GetTypeElement() ?.Equals(gizmoType?.GetTypeElement()) == true) { if (i == 1) { secondParamCorrect = true; } gizmoName = param.DeclaredName; } } var expectedDeclaration = new MethodSignature(predefinedType.Void, true, new[] { derivedType, gizmoType }, new[] { derivedName, gizmoName }); var match = expectedDeclaration.Match(methodDeclaration); if (methodDeclaration.Params.ParameterDeclarations.Count == 2) { if (firstParamCorrect && secondParamCorrect) { match &= ~MethodSignatureMatch.IncorrectParameters; } else if (!firstParamCorrect && secondParamCorrect && match == MethodSignatureMatch.IncorrectParameters) { // TODO: Should this be ExpectedComponentWarning? consumer.AddHighlighting(new ParameterNotDerivedFromComponentWarning(methodDeclaration.Params.ParameterDeclarations.First())); return; } } AddMethodSignatureInspections(consumer, methodDeclaration, expectedDeclaration, match); }
public Method.IMethod GetMethod(string name, List <IType> param, IType[] genericArguments, IType returnType = null, bool declaredOnly = false) { return(null); }
public void AddType(IType type) { _container.AddType(type); }
public static bool ShouldBeSyntheticType(IType type) { return(type is PrimaryType || type is PackageType || type is SequenceType || type is DictionaryType || type is EnumType); }
public bool CanAssignTo(IType type) { return(false); }
public static bool IsAllowedPrimitiveType(IType type) { return(!(type is DictionaryType || type is SequenceType || type.IsPrimaryType(KnownPrimaryType.Stream))); }
private void Bind() { var cb = this; foreach (_ClassBind _class in cb.ScriptsToBind) { //添加脚本 string classType = $"{_class.Namespace + (_class.Namespace == "" ? "" : ".")}{_class.Class}"; if (!Init.appdomain.LoadedTypes.ContainsKey(classType)) { Log.PrintError($"自动绑定{this.name}出错:{classType}不存在,已跳过"); continue; } IType type = Init.appdomain.LoadedTypes[classType]; Type t = type.ReflectionType;//获取实际属性 var instance = _class.UseConstructor ? Init.appdomain.Instantiate(classType) : new ILTypeInstance(type as ILType, false); var clrInstance = cb.gameObject.AddComponent<MonoBehaviourAdapter.Adaptor>(); clrInstance.enabled = false; clrInstance.ILInstance = instance; clrInstance.AppDomain = Init.appdomain; instance.CLRInstance = clrInstance; //绑定数据 if (_class.RequireBindFields) { _class.BoundData = false; var fields = _class.Fields.ToArray(); foreach (_ClassField field in fields) { object obj = new object(); try { if (field.fieldType == _ClassField.FieldType.Short) { obj = int.Parse(field.value); _class.BoundData = true; } else if (field.fieldType == _ClassField.FieldType.UShort) { obj = ushort.Parse(field.value); _class.BoundData = true; } else if (field.fieldType == _ClassField.FieldType.Int) { obj = short.Parse(field.value); _class.BoundData = true; } else if (field.fieldType == _ClassField.FieldType.UInt) { obj = uint.Parse(field.value); _class.BoundData = true; } else if (field.fieldType == _ClassField.FieldType.Long) { obj = long.Parse(field.value); _class.BoundData = true; } else if (field.fieldType == _ClassField.FieldType.ULong) { obj = ulong.Parse(field.value); _class.BoundData = true; } else if (field.fieldType == _ClassField.FieldType.Float) { obj = float.Parse(field.value); _class.BoundData = true; } else if (field.fieldType == _ClassField.FieldType.Decimal) { obj = decimal.Parse(field.value); _class.BoundData = true; } else if (field.fieldType == _ClassField.FieldType.Double) { obj = Double.Parse(field.value); _class.BoundData = true; } else if (field.fieldType == _ClassField.FieldType.String) { obj = field.value; _class.BoundData = true; } else if (field.fieldType == _ClassField.FieldType.Bool) { field.value = field.value.ToLower(); obj = field.value == "true"; _class.BoundData = true; } else if (field.fieldType == _ClassField.FieldType.GameObject) { GameObject go = field.gameObject; if (go == null) { try { go = field.value == "${this}" ? this.gameObject : GameObject.Find(field.value); if (go == null) //找父物体 { go = FindSubGameObject(field); if (go == null) //如果父物体还不存在 { continue; } } } catch (Exception ex) //找父物体(如果抛出空异常) { go = FindSubGameObject(field); if (go == null) //如果父物体还不存在 { continue; } } } obj = go; _class.BoundData = true; } else if (field.fieldType == _ClassField.FieldType.UnityComponent) { GameObject go = field.gameObject; if (go == null) { try { if (field.value.Contains(".")) { field.value = field.value.Remove(field.value.IndexOf(".", StringComparison.Ordinal)); } go = field.value == "${this}" ? this.gameObject : GameObject.Find(field.value); if (go == null) //找父物体 { go = FindSubGameObject(field); if (go == null) //如果父物体还不存在 { continue; } } } catch (Exception ex) //找父物体(如果抛出空异常) { go = FindSubGameObject(field); if (go == null) //如果父物体还不存在 { continue; } } } var tp = t.GetField(field.fieldName, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static); if (tp != null) { string tName = tp.FieldType.Name; if (tp.FieldType.Assembly.ToString().Contains("ILRuntime")) //如果在热更中 { var components = go.GetComponents<MonoBehaviourAdapter.Adaptor>(); foreach (var c in components) { if (c.ILInstance.Type.Name == tName) { obj = c.ILInstance; _class.BoundData = true; break; } } } else { var component = go.GetComponents<Component>().ToList() .Find(c => c.GetType().ToString().Contains(tName)); if (component != null) { obj = component; _class.BoundData = true; } } } } else if (field.fieldType == _ClassField.FieldType.HotUpdateResource) { obj = Assets.LoadAsset(field.value, typeof(UnityEngine.Object)).asset; _class.BoundData = true; } } catch (Exception except) { Log.PrintError( $"自动绑定{this.name}出错:{classType}.{field.fieldName}获取值{field.value}出错:{except.Message},已跳过"); } //如果有数据再绑定 if (_class.BoundData) { var fi = t.GetField(field.fieldName, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static); if (fi != null) { try { fi.SetValue(clrInstance.ILInstance, obj); } catch (Exception e) { Log.PrintError( $"自动绑定{this.name}出错:{classType}.{field.fieldName}赋值出错:{e.Message},已跳过"); } } else { //没FieldInfo尝试PropertyInfo var pi = t.GetProperty(field.fieldName, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static); if (pi != null) { pi.SetValue(clrInstance.ILInstance, obj); } else { Log.PrintError($"自动绑定{this.name}出错:{classType}不存在{field.fieldName},已跳过"); } } } } } //是否激活 if (_class.ActiveAfter) { if (_class.BoundData == false && _class.RequireBindFields) { Log.PrintError($"自动绑定{this.name}出错:{classType}没有成功绑定数据,无法自动激活,请手动!"); continue; } clrInstance.enabled = true; clrInstance.Awake(); } } Destroy(cb); }
public bool CanAssignTo(IType type) { return(this.type.CanAssignTo(type)); }
public SyntheticType(IType baseType) { if (!ShouldBeSyntheticType(baseType)) { throw new ArgumentException("{0} is not a valid type for SyntheticType", baseType.ToString()); } // gosdk: Ensure the generated name does not collide with existing type names BaseType = baseType; IType elementType = getElementType(baseType); if (elementType is PrimaryType) { var type = (elementType as PrimaryType).Type; if (type == KnownPrimaryType.Boolean) { Name += "Bool"; } else if (type == KnownPrimaryType.ByteArray) { Name += "ByteArray"; } else if (type == KnownPrimaryType.Double) { Name += "Float64"; } else if (type == KnownPrimaryType.Int) { Name += "Int32"; } else if (type == KnownPrimaryType.Long) { Name += "Int64"; } else if (type == KnownPrimaryType.Stream) { Name += "ReadCloser"; } else if (type == KnownPrimaryType.String) { Name += "String"; } else if (type == KnownPrimaryType.TimeSpan) { Name += "TimeSpan"; } else if (type == KnownPrimaryType.Base64Url) { Name += "Base64Url"; } else if (type == KnownPrimaryType.UnixTime) { Name += "UnixTime"; } } else if (elementType is InterfaceType) { Name += "Object"; } else if (elementType is PackageType) { Name += (elementType as PackageType).Member; } else if (elementType is EnumType) { Name += "String"; } else { Name += elementType.Name; } Property p = new Property(); p.SerializedName = "value"; p.Name = "Value"; p.Type = baseType; Properties.Add(p); }
private static bool TraverseMembers( ISessionFactoryImplementor sessionFactory, Stack<MemberMetadata> memberPaths, IEntityPersister currentEntityPersister, out IType mappedType, out IEntityPersister entityPersister, out IAbstractComponentType component, out string memberPath) { // Traverse the members that were traversed by the TryGetAllMemberMetadata method in the reverse order and try to keep // tracking the entity persister until all members are traversed. var member = memberPaths.Pop(); var currentType = GetPropertyType(currentEntityPersister, member.Path); IAbstractComponentType currentComponentType = null; while (memberPaths.Count > 0 && currentType != null) { memberPath = member.Path; var convertType = member.ConvertType; member = memberPaths.Pop(); switch (currentType) { case IAssociationType associationType: ProcessAssociationType( associationType, sessionFactory, member, convertType, out currentType, out currentEntityPersister, out currentComponentType); break; case IAbstractComponentType componentType: currentComponentType = componentType; currentType = TryGetComponentPropertyType(componentType, member.Path); if (currentEntityPersister != null) { // q.Component.Prop member = new MemberMetadata( memberPath + "." + member.Path, member.ConvertType, member.HasIndexer); } break; default: // q.Prop.NotMappedProp currentType = null; currentEntityPersister = null; currentComponentType = null; break; } } // When traversed to the top of the expression, return the current tracking values if (memberPaths.Count == 0) { memberPath = currentEntityPersister != null || currentComponentType != null ? member.Path : null; mappedType = GetType(currentEntityPersister, currentType, member, sessionFactory); entityPersister = currentEntityPersister; component = currentComponentType; return mappedType != null; } // Member not mapped memberPath = null; mappedType = null; entityPersister = null; component = null; return false; }
public GenericInstance(IType type, params IType[] args) : this(type, (IEnumerable <IType>)args) { }
private static bool ProcessMembersMetadataResult( MemberMetadataResult metadataResult, ISessionFactoryImplementor sessionFactory, out IType mappedType, out IEntityPersister entityPersister, out IAbstractComponentType component, out string memberPath) { if (!TryGetEntityPersister(metadataResult.EntityName, null, sessionFactory, out var currentEntityPersister)) { // Failed to find the starting entity name, due to: // - Querying a type that is not related to any entity e.g. s.Query<NotRelatedType>().Where(a => a.Type == "A") memberPath = null; mappedType = null; entityPersister = null; component = null; return false; } if (metadataResult.MemberPaths.Count == 0) // The expression do not contain any member expressions { if (metadataResult.ConvertType != null) { mappedType = TryGetEntityPersister( currentEntityPersister, metadataResult.ConvertType, sessionFactory, out var convertPersister) ? convertPersister.EntityMetamodel.EntityType // ((Subclass)q) : TypeFactory.GetDefaultTypeFor(metadataResult.ConvertType); // ((NotMapped)q) } else { mappedType = currentEntityPersister.EntityMetamodel.EntityType; // q } memberPath = null; component = null; entityPersister = currentEntityPersister; return mappedType != null; } // If there was a cast right after the constant expression that contains the IEntityNameProvider instance, we have // to update the entity persister according to it, otherwise use the value returned by TryGetAllMemberMetadata method. if (metadataResult.ConvertType != null) { if (!TryGetEntityPersister( currentEntityPersister, metadataResult.ConvertType, sessionFactory, out var convertPersister)) // ((NotMapped)q).Id { memberPath = null; mappedType = null; entityPersister = null; component = null; return false; } currentEntityPersister = convertPersister; // ((Subclass)q).Id } return TraverseMembers( sessionFactory, metadataResult.MemberPaths, currentEntityPersister, out mappedType, out entityPersister, out component, out memberPath); }
private static void HandleExpressionBody(IBlock body, CSharpElementFactory factory, IType type, string name, DisposableMarker <IReferenceExpression> marker, IReferenceExpression originValue) { var statement = body.Statements.First().NotNull("body.Statements.First() != null"); StatementUtil.InsertStatement(factory.CreateStatement("$0 $1;", type, name), ref statement, true); var updatedReference = marker.Find(body).NotNull("marker.Find(body) != null"); updatedReference.ReplaceBy(factory.CreateExpression("($0 = $1)", name, originValue.Copy())); }