当前位置: 首页>>代码示例>>C#>>正文


C# ITypeSymbol.GetMembers方法代码示例

本文整理汇总了C#中ITypeSymbol.GetMembers方法的典型用法代码示例。如果您正苦于以下问题:C# ITypeSymbol.GetMembers方法的具体用法?C# ITypeSymbol.GetMembers怎么用?C# ITypeSymbol.GetMembers使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在ITypeSymbol的用法示例。


在下文中一共展示了ITypeSymbol.GetMembers方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: ReadSymbol

 /// <summary>
 /// TODO: improve this:
 /// there should be a classsymbol reader which
 /// calls the other readers. Because currently this
 /// method is implemented by every reader although 
 /// the reader will only handle the symbols for which it is
 /// responsible
 /// </summary>
 /// <param name="typeSymbol"></param>
 protected virtual void ReadSymbol(ITypeSymbol typeSymbol)
 {
     var properties = typeSymbol.GetMembers().OfType<IPropertySymbol>();
     foreach (var property in properties) ReadSymbol(property);
     var methods = typeSymbol.GetMembers().OfType<IMethodSymbol>();
     foreach (var method in methods) ReadSymbol(method);
     var events = typeSymbol.GetMembers().OfType<IEventSymbol>();
     foreach (var @event in events) ReadSymbol(@event);
 }
开发者ID:pgenfer,项目名称:mixinSharp,代码行数:18,代码来源:SemanticTypeReaderBase.cs

示例2: TryGetAllEnumMembers

        private static bool TryGetAllEnumMembers(
            ITypeSymbol enumType,
            Dictionary<long, ISymbol> enumValues)
        {
            foreach (var member in enumType.GetMembers())
            {
                // skip `.ctor` and `__value`
                var fieldSymbol = member as IFieldSymbol;
                if (fieldSymbol == null || fieldSymbol.Type.SpecialType != SpecialType.None)
                {
                    continue;
                }

                if (fieldSymbol.ConstantValue == null)
                {
                    // We have an enum that has problems with it (i.e. non-const members).  We won't
                    // be able to determine properly if the switch is complete.  Assume it is so we
                    // don't offer to do anything.
                    return false;
                }

                // Multiple enum members may have the same value.  Only consider the first one
                // we run int.
                var enumValue = IntegerUtilities.ToInt64(fieldSymbol.ConstantValue);
                if (!enumValues.ContainsKey(enumValue))
                {
                    enumValues.Add(enumValue, fieldSymbol);
                }
            }

            return true;
        }
开发者ID:xyh413,项目名称:roslyn,代码行数:32,代码来源:PopulateSwitchHelpers.cs

示例3: FindWidgetField

		public static IFieldSymbol FindWidgetField (ITypeSymbol cls, string name)
		{
			foreach (var field in cls.GetMembers ().OfType<IFieldSymbol> ()) {
				if (name == GetWidgetFieldName (field))
					return field;
			}
			return null;
		}
开发者ID:pabloescribanoloza,项目名称:monodevelop,代码行数:8,代码来源:ClassUtils.cs

示例4: CompileTimeLoopContext

 internal CompileTimeLoopContext(string fullPath, ITypeSymbol symbol)
     : base(fullPath, symbol)
 {
     //Get all Members of symbol which are accessible properties and build a context for each of them
       Members = symbol.GetMembers().OfType<IPropertySymbol>()
                            .Where(x => x.DeclaredAccessibility == Accessibility.Public || x.DeclaredAccessibility == Accessibility.Internal)
                            .Select(x => new Context($"{fullPath}.{x.Name}", x.Type)).ToList();
       Index = -1; //To make MoveNext behave like other MoveNexts (e.g. First call MoveNext before you do anything else);
 }
开发者ID:Noxum,项目名称:CompiledHandlebars,代码行数:9,代码来源:Context.cs

示例5: IsStructMutable

        private bool IsStructMutable(ITypeSymbol type)
        {
            Contract.Requires(type.IsValueType);

            var members = type.GetMembers().OfType<IFieldSymbol>().ToList();
            
            // If all members are immutable, then the struct could be considered as shallow immutable
            if (members.All(m => (m.IsReadOnly || m.IsStatic || m.IsConst)))
            {
                return false;
            }

            // Potentially additional logic could be added to consider as immutable even types that
            // has non-readonly fields that are not changed!
            return true;
        }
开发者ID:SergeyTeplyakov,项目名称:ErrorProne.NET,代码行数:16,代码来源:NonPureMethodsOnReadonlyStructs.cs

示例6: GenerateWriteGrain

        private static ClassDeclarationSyntax GenerateWriteGrain(ClassDeclarationSyntax grainClass, ITypeSymbol swmrInterface, int readReplicaCount)
        {
            string grainName = grainClass.Identifier.Text;
            string writerGrainName = SwmrUtils.GetWriteInterfaceName(grainName);
            string writerInterfaceName = SwmrUtils.GetWriteInterfaceName(swmrInterface.Name);
            ClassDeclarationSyntax writerGrain = GenerateClassSqueleton(writerGrainName).WithBaseList(RoslynUtils.BaseList(new[] { "Grain", writerInterfaceName }));

            writerGrain = RoslynUtils.AddField(writerGrain, "ITopology<string>", "_topology");
            writerGrain = writerGrain.AddMembers(GenerateOnActivateAsyncMethod(readReplicaCount));

            string readReplicaInterfaceName = SwmrUtils.GetReadReplicaInterfaceName(swmrInterface.Name);
            foreach (ISymbol member in swmrInterface.GetMembers())
            {
                IMethodSymbol methodSymbol = member as IMethodSymbol;
                if (methodSymbol == null || IsReadOnlyMethod(methodSymbol) || new MethodInspector(methodSymbol).MethodName == "GetState")
                {
                    continue;
                }

                MethodInspector methodInspector = new MethodInspector(methodSymbol);
                MethodDeclarationSyntax methodImpl = GenerateMethodDeclaration(methodInspector);
                methodImpl = SwmrUtils.AddSessionIdParameter(methodImpl).AddModifiers(SF.Token(SyntaxKind.PublicKeyword), SF.Token(SyntaxKind.AsyncKeyword)).WithSemicolonToken(SF.Token(SyntaxKind.None));

                BlockSyntax statmentBlock = SF.Block();
                statmentBlock = AddStatement(statmentBlock, "string grainId = this.GetPrimaryKeyString();");
                statmentBlock = AddStatement(statmentBlock, string.Format("{0} grain = GrainFactory.GetGrain<{0}>(grainId);", swmrInterface.Name));
                statmentBlock = AddStatement(statmentBlock, String.Format("{0} await grain.{1}({2});", methodInspector.ReturnType != "Task"? "var result =" : "", methodInspector.MethodName, string.Join(", ", methodInspector.MethodParams.Keys)));
                statmentBlock = AddStatement(statmentBlock, "GrainState state = await grain.GetState();");
                statmentBlock = AddStatement(statmentBlock, "string sessionNode = _topology.GetNode(sessionId);");
                statmentBlock = AddStatement(statmentBlock, "IEnumerable<string> otherNodes = _topology.Nodes.Where(node => node != sessionNode);");

                ForEachStatementSyntax forEachStatement = SF.ForEachStatement(
                    SF.PredefinedType(SF.Token(SyntaxKind.StringKeyword)),
                    SF.Identifier("node"),
                    SF.IdentifierName("otherNodes"),
                    SF.Block(SF.ParseStatement(GenerateSetStateStmt(readReplicaInterfaceName, @"node")))
                );

                statmentBlock = statmentBlock.AddStatements(forEachStatement);
                statmentBlock =
                    AddStatement(statmentBlock, (string.Format("{0} {1}", "await",
                            GenerateSetStateStmt(readReplicaInterfaceName, @"sessionNode"))));
                if (methodInspector.ReturnType != "Task")
                {
                    statmentBlock = AddStatement(statmentBlock, "return result;");
                }
                methodImpl = methodImpl.WithBody(statmentBlock);
                writerGrain = writerGrain.AddMembers(methodImpl);
            }

            return writerGrain;
        }
开发者ID:cdsalmons,项目名称:OrleansTemplates,代码行数:52,代码来源:SwmrGrainsGenerator.cs

示例7: ImplementConstructorBody

            private SyntaxNode ImplementConstructorBody(BlockSyntax declaration,
                                                                                 string sourcename,
                                                                                 ITypeSymbol targetTypeInfo,
                                                                                 ITypeSymbol sourceType)
            {
                var missingprops = GetMissingProperties(declaration, targetTypeInfo);

                var newproperties =
                    sourceType.GetMembers().Where(x => x.Kind == SymbolKind.Property).Cast<IPropertySymbol>().Where(x => x.IsMissing(missingprops));
                var newExpression = declaration.AddStatements(
                    newproperties.Select(x =>
                                             SyntaxFactory.AssignmentExpression(SyntaxKind.SimpleAssignmentExpression,
                                                                                SyntaxFactory.IdentifierName(x.Name),
                                                                                SyntaxFactory.MemberAccessExpression(
                                                                                    SyntaxKind.SimpleMemberAccessExpression,
                                                                                    SyntaxFactory.IdentifierName(sourcename),
                                                                                    SyntaxFactory.IdentifierName(x.Name))))
                        .Cast<ExpressionSyntax>().Select(SyntaxFactory.ExpressionStatement).ToArray<StatementSyntax>());
                return newExpression;
            }
开发者ID:jarlrasm,项目名称:PhilTheCartographer,代码行数:20,代码来源:FillConstrutorBodyRefactoring.cs

示例8: AppendConstant

		void AppendConstant (StringBuilder sb, ITypeSymbol constantType, object constantValue, bool useNumericalEnumValue = false)
		{
			if (constantValue is string) {
				sb.Append (Highlight ("\"" + MonoDevelop.Ide.TypeSystem.Ambience.EscapeText ((string)constantValue) + "\"", colorStyle.String));
				return;
			}
			if (constantValue is char) {
				sb.Append (Highlight ("'" + constantValue + "'", colorStyle.String));
				return;
			}
			if (constantValue is bool) {
				sb.Append (Highlight ((bool)constantValue ? "true" : "false", colorStyle.KeywordConstants));
				return;
			}

			if (constantValue == null) {
				if (constantType.IsValueType) {
					// structs can never be == null, therefore it's the default value.
					sb.Append (Highlight ("default", colorStyle.KeywordSelection) + "(" + GetTypeReferenceString (constantType) + ")");
				} else {
					sb.Append (Highlight ("null", colorStyle.KeywordConstants));
				}
				return;
			}
			//			TODOδ
			//			while (IsNullableType (constantType))
			//				constantType = NullableType.GetUnderlyingType (constantType);
			if (constantType.TypeKind == TypeKind.Enum) {
				foreach (var field in constantType.GetMembers ().OfType<IFieldSymbol> ()) {
					if (field.ConstantValue == constantValue) {
						if (useNumericalEnumValue) {
							sb.Append (Highlight (string.Format ("0x{0:X}", field.ConstantValue), colorStyle.Number));
						} else {
							sb.Append (GetTypeReferenceString (constantType) + "." + FilterEntityName (field.Name));
						}
						return;
					}
				}
				// try to decompose flags
				if (constantType.GetAttributes ().Any (attr => attr.AttributeClass.Name == "FlagsAttribute" && attr.AttributeClass.ContainingNamespace.Name == "System")) {
					var val = GetUlong (constantValue.ToString ());
					var outVal = 0UL;
					var fields = new List<IFieldSymbol> ();
					foreach (var field in constantType.GetMembers ().OfType<IFieldSymbol> ()) {
						if (field.ConstantValue == null)
							continue;
						var val2 = GetUlong (field.ConstantValue.ToString ());
						if ((val & val2) == val2) {
							fields.Add (field);
							outVal |= val2;
						}
					}

					if (val == outVal && fields.Count > 1) {
						for (int i = 0; i < fields.Count; i++) {
							if (i > 0)
								sb.Append (" | ");
							var field = fields [i];
							sb.Append (GetTypeReferenceString (constantType) + "." + FilterEntityName (field.Name));
						}
						return;
					}
				}

				sb.Append ("(" + GetTypeReferenceString (constantType) + ")" + Highlight (constantValue.ToString (), colorStyle.Number));
				return;
			}
			sb.Append (Highlight (MonoDevelop.Ide.TypeSystem.Ambience.EscapeText (constantValue.ToString ()), colorStyle.Number));
		}
开发者ID:kdubau,项目名称:monodevelop,代码行数:69,代码来源:SignatureMarkupCreator.cs

示例9: HintPropertyValues

 private IEnumerable<CompletionData> HintPropertyValues(ITypeSymbol propertyType)
 {
     if (propertyType.TypeKind == TypeKind.Enum)
     {
         return propertyType.GetMembers().Where(m => m.Kind == SymbolKind.Field).Select(m => new CompletionData(m.Name));
     }
     if (CheckType(propertyType, typeof(bool)))
     {
         return new[]
         {
             new CompletionData("false"),
             new CompletionData("true")
         };
     }
     return Enumerable.Empty<CompletionData>();
 }
开发者ID:adamjez,项目名称:dotvvm,代码行数:16,代码来源:MetadataControlResolver.cs

示例10: CheckIfVoidReturningDelegateType

        /// <summary>
        /// Check if the method is a void returning delegate type
        /// </summary>
        /// <param name="convertedType"></param>
        /// <returns>
        /// Returns false if analysis failed or if not a void-returning delegate type
        /// Returns true if the inputted node has a converted type that is a void-returning delegate type
        /// </returns>
        private bool CheckIfVoidReturningDelegateType(ITypeSymbol convertedType)
        {
            if (convertedType != null && convertedType.TypeKind.Equals(TypeKind.Delegate))
            {
                var invoke = convertedType.GetMembers("Invoke").FirstOrDefault() as IMethodSymbol;

                if (invoke != null)
                {
                    return invoke.ReturnsVoid;
                }
            }

            return false;
        }
开发者ID:maggiemsft,项目名称:roslyn-analyzers,代码行数:22,代码来源:AsyncLambdaAnalyzer.cs

示例11: GenerateReadGrain

        private static ClassDeclarationSyntax GenerateReadGrain(ClassDeclarationSyntax grainClass, ITypeSymbol swmrInterface, int readReplicaCount)
        {
            string readGrainName = SwmrUtils.GetReadInterfaceName(grainClass.Identifier.Text);
            string readerInterfaceName = SwmrUtils.GetReadInterfaceName(swmrInterface.Name);
            ClassDeclarationSyntax readGrain = GenerateClassSqueleton(readGrainName).WithAttributeLists(AttributeUtils.AttributeListList(AttributeUtils.Attribute(StatelessWorkerAttributeName))).WithBaseList(RoslynUtils.BaseList(new[] { "Grain", readerInterfaceName }));
            readGrain = RoslynUtils.AddField(readGrain, "ITopology<string>", "_topology");
            readGrain = readGrain.AddMembers(GenerateOnActivateAsyncMethod(readReplicaCount));

            string readReplicaInterfaceName = SwmrUtils.GetReadReplicaInterfaceName(swmrInterface.Name);

            foreach (ISymbol member in swmrInterface.GetMembers())
            {
                IMethodSymbol methodSymbol = member as IMethodSymbol;
                if (methodSymbol == null || !IsReadOnlyMethod(methodSymbol))
                {
                    continue;
                }

                MethodInspector methodInspector = new MethodInspector(methodSymbol);
                string parameters = "string sessionId";
                if (methodInspector.MethodParams.Any())
                {
                    parameters = string.Join(", ", methodInspector.MethodParams.Select(param => string.Format("{0} {1}", param.Value, param.Key))) + " ," + parameters;
                }

                var method = RoslynUtils.ParseMethod(string.Format(
    @"
        public {0} {1}({2})
        {{
            string sessionNode = _topology.GetNode(sessionId);
            var readReplica = GrainFactory.GetGrain<{3}>(sessionNode);
            return readReplica.{1}({4});
        }}", methodInspector.ReturnType, methodInspector.MethodName, parameters, readReplicaInterfaceName, string.Join(", ", methodInspector.MethodParams.Keys)));

                readGrain =
                    readGrain.AddMembers(
                        method.WithLeadingTrivia(SF.EndOfLine("")));
            }
            return readGrain;
        }
开发者ID:cdsalmons,项目名称:OrleansTemplates,代码行数:40,代码来源:SwmrGrainsGenerator.cs

示例12: GetInsertionPoints

		public static List<InsertionPoint> GetInsertionPoints (IReadonlyTextDocument data, MonoDevelop.Ide.TypeSystem.ParsedDocument parsedDocument, ITypeSymbol type, int part)
		{
			if (data == null)
				throw new ArgumentNullException (nameof (data));
			if (parsedDocument == null)
				throw new ArgumentNullException (nameof (parsedDocument));
			if (type == null)
				throw new ArgumentNullException (nameof (type));
			if (!type.IsDefinedInSource ())
				throw new ArgumentException ("The given type needs to be defined in source code.", nameof (type));

			// update type from parsed document, since this is always newer.
			//type = parsedDocument.GetInnermostTypeDefinition (type.GetLocation ()) ?? type;
			List<InsertionPoint> result = new List<InsertionPoint> ();
			//var realStartLocation = data.OffsetToLocation (offset);
			var model = parsedDocument.GetAst<SemanticModel> ();
			type = model.GetEnclosingNamedType (part, default(CancellationToken)) as ITypeSymbol ?? type;
			var sourceSpan = new TextSpan (part, 0);

			var filePath = data.FileName;
			var declaringType = type.DeclaringSyntaxReferences.FirstOrDefault (dsr => dsr.SyntaxTree.FilePath == filePath && dsr.Span.Contains (sourceSpan)) ?? type.DeclaringSyntaxReferences.FirstOrDefault ();
			if (declaringType == null)
				return result;
			var openBraceToken = declaringType.GetSyntax ().ChildTokens ().FirstOrDefault (t => t.IsKind (SyntaxKind.OpenBraceToken));
			if (!openBraceToken.IsMissing) {
				var domLocation = data.OffsetToLocation (openBraceToken.SpanStart);
				result.Add (GetInsertionPosition (data, domLocation.Line, domLocation.Column));
				//			result.Add (GetInsertionPosition (data, realStartLocation.Line, realStartLocation.Column));
				result [0].LineBefore = NewLineInsertion.None;
			}
			foreach (var member in type.GetMembers ()) {
				if (member.IsImplicitlyDeclared || !member.IsDefinedInSource())
					continue;
				//var domLocation = member.BodyRegion.End;
				foreach (var loc in member.DeclaringSyntaxReferences) {
					if (loc.SyntaxTree.FilePath != declaringType.SyntaxTree.FilePath || !declaringType.Span.Contains (sourceSpan))
						continue;
					var domLocation = data.OffsetToLocation (loc.Span.End);

					if (domLocation.Line <= 0) {
						var lineSegment = data.GetLineByOffset (loc.Span.Start);
						if (lineSegment == null)
							continue;
						domLocation = new DocumentLocation (lineSegment.LineNumber, lineSegment.Length + 1);
					}
					result.Add (GetInsertionPosition (data, domLocation.Line, domLocation.Column));
					break;
				}
			}

			result [result.Count - 1].LineAfter = NewLineInsertion.None;
			CheckStartPoint (data, result [0], result.Count == 1);
			if (result.Count > 1) {
				result.RemoveAt (result.Count - 1); 
				NewLineInsertion insertLine;
				var typeSyntaxReference = type.DeclaringSyntaxReferences.FirstOrDefault (r => r.Span.Contains (sourceSpan));

				var lineBefore = data.GetLineByOffset (typeSyntaxReference.Span.End).PreviousLine;
				if (lineBefore != null && lineBefore.Length == lineBefore.GetIndentation (data).Length) {
					insertLine = NewLineInsertion.None;
				} else {
					insertLine = NewLineInsertion.Eol;
				}
				// search for line start
				var line = data.GetLineByOffset (typeSyntaxReference.Span.End);
				int col = typeSyntaxReference.Span.End - line.Offset;
				if (line != null) {
					var lineOffset = line.Offset;
					col = Math.Min (line.Length, col);
					while (lineOffset + col - 2 >= 0 && col > 1 && char.IsWhiteSpace (data.GetCharAt (lineOffset + col - 2)))
						col--;
				}
				result.Add (new InsertionPoint (new DocumentLocation (line.LineNumber, col), insertLine, NewLineInsertion.Eol));
				CheckEndPoint (data, result [result.Count - 1], result.Count == 1);
			}

//			foreach (var region in parsedDocument.UserRegions.Where (r => type.BodyRegion.IsInside (r.Region.Begin))) {
//				result.Add (new InsertionPoint (new DocumentLocation (region.Region.BeginLine + 1, 1), NewLineInsertion.Eol, NewLineInsertion.Eol));
//				result.Add (new InsertionPoint (new DocumentLocation (region.Region.EndLine, 1), NewLineInsertion.Eol, NewLineInsertion.Eol));
//				result.Add (new InsertionPoint (new DocumentLocation (region.Region.EndLine + 1, 1), NewLineInsertion.Eol, NewLineInsertion.Eol));
//			}
			result.Sort ((left, right) => left.Location.CompareTo (right.Location));
			//foreach (var res in result)
			//	Console.WriteLine (res);
			return result;
		}
开发者ID:pabloescribanoloza,项目名称:monodevelop,代码行数:86,代码来源:InsertionPointService.cs

示例13: VerifyTypeMethods

        internal static void VerifyTypeMethods(ContextReporter context, ITypeSymbol type)
        {
            var methods = type.GetMembers()
                .OfType<IMethodSymbol>()
                .Where(x => x.MethodKind == MethodKind.Ordinary)
                .Where(x => x.DeclaredAccessibility == Accessibility.Public)
                .Where(x => !x.IsStatic)
                .ToArray();

            var alreadyAnalyzed = new HashSet<ITypeSymbol>();
            foreach (var method in methods)
            {
                var methodDecl = method.DeclaringSyntaxReferences[0].GetSyntax() as MethodDeclarationSyntax;
                if (methodDecl == null) return;

                VerifyType(context, methodDecl.ReturnType.GetLocation(), method.ReturnType, alreadyAnalyzed);
                foreach (var item in method.Parameters.Zip(methodDecl.ParameterList.Parameters, (symbol, syntax) => new { symbol, syntax }))
                {
                    VerifyType(context, item.syntax.Type.GetLocation(), item.symbol.Type, alreadyAnalyzed);
                }
            }
        }
开发者ID:neuecc,项目名称:PhotonWire,代码行数:22,代码来源:SerializeTypeMustBeDataContractAnalyzer.cs

示例14: IsExcludedFromMapping

        private static bool IsExcludedFromMapping(IPropertySymbol property, ITypeSymbol metadataClass)
        {
            if (metadataClass != null)
            {
                property = (metadataClass.GetMembers(property.Name).FirstOrDefault() as IPropertySymbol) ?? property;
            }

            return property
                .GetAttributes()
                .Any(a => a.AttributeClass.ToString() == "NCR.Engage.RoslynAnalysis.ExcludeFromMappingAttribute");
        }
开发者ID:NCR-Engage,项目名称:MapEnforcerAnalyzer,代码行数:11,代码来源:DiagnosticAnalyzer.cs

示例15: GetSourceProperties

 private static IEnumerable<IPropertySymbol> GetSourceProperties(SemanticModel semModel, ITypeSymbol sourceClass, ITypeSymbol sourceMetadataClass)
 {
     return sourceClass
         .GetMembers()
         .Where(m => m.Kind == SymbolKind.Property)
         .Cast<IPropertySymbol>()
         .Where(p => !IsExcludedFromMapping(p, sourceMetadataClass));
 }
开发者ID:NCR-Engage,项目名称:MapEnforcerAnalyzer,代码行数:8,代码来源:DiagnosticAnalyzer.cs


注:本文中的ITypeSymbol.GetMembers方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。