• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

C# MetadataImageReference类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C#中MetadataImageReference的典型用法代码示例。如果您正苦于以下问题:C# MetadataImageReference类的具体用法?C# MetadataImageReference怎么用?C# MetadataImageReference使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



MetadataImageReference类属于命名空间,在下文中一共展示了MetadataImageReference类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。

示例1: TestOverloadResolutionWithDiff

        internal void TestOverloadResolutionWithDiff(string source, MetadataReference[] additionalRefs = null)
        {
            // The mechanism of this test is: we build the bound tree for the code passed in and then extract
            // from it the nodes that describe the method symbols. We then compare the description of
            // the symbols given to the comment that follows the call.

            var mscorlibRef = new MetadataImageReference(ProprietaryTestResources.NetFX.v4_0_30316_17626.mscorlib.AsImmutableOrNull(), display: "mscorlib");
            var references = new[] { mscorlibRef }.Concat(additionalRefs ?? SpecializedCollections.EmptyArray<MetadataReference>());

            var compilation = CreateCompilation(source, references, TestOptions.ReleaseDll);

            var method = (SourceMethodSymbol)compilation.GlobalNamespace.GetTypeMembers("C").Single().GetMembers("M").Single();
            var diagnostics = new DiagnosticBag();
            var block = MethodCompiler.BindMethodBody(method, new TypeCompilationState(method.ContainingType, compilation, null), diagnostics);
            var tree = BoundTreeDumperNodeProducer.MakeTree(block);
            var results = string.Join("\n", tree.PreorderTraversal().Select(edge => edge.Value)
                .Where(x => x.Text == "method" && x.Value != null)
                .Select(x => x.Value)
                .ToArray());

            // var r = string.Join("\n", tree.PreorderTraversal().Select(edge => edge.Value).ToArray();

            var expected = string.Join("\n", source
                .Split(new[] { "\r\n" }, System.StringSplitOptions.RemoveEmptyEntries)
                .Where(x => x.Contains("//-"))
                .Select(x => x.Substring(x.IndexOf("//-") + 3))
                .ToArray());

            AssertEx.Equal(expected, results);
        }
开发者ID:modulexcite,项目名称:pattern-matching-csharp,代码行数:30,代码来源:OverloadResolutionTestBase.cs


示例2: CanBeReferencedByName

        public void CanBeReferencedByName()
        {
            var vbText = @"
Public Interface I
    Property P(x As Integer)
End Interface
";
            var vbcomp = VisualBasicCompilation.Create(
                "Test",
                new[] { VisualBasicSyntaxTree.ParseText(vbText) },
                new[] { MscorlibRef_v4_0_30316_17626 },
                new VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary));

            var metaDataArray = vbcomp.EmitToArray();

            var ref1 = new MetadataImageReference(metaDataArray, embedInteropTypes: true);

            var text = @"class C : I {}";
            var tree = Parse(text);
            var comp = CreateCompilation(new [] { tree }, new [] { ref1 });

            var t = comp.GetTypeByMetadataName("I");
            Assert.Empty(t.GetMembersUnordered().Where(x => x.Kind == SymbolKind.Method && !x.CanBeReferencedByName));
            Assert.False(t.GetMembersUnordered().Where(x => x.Kind == SymbolKind.Property).First().CanBeReferencedByName); //there's only one.
        }
开发者ID:EkardNT,项目名称:Roslyn,代码行数:25,代码来源:CrossLanguageTests.cs


示例3: MetadataImageReference_Module_WithXxx

        public void MetadataImageReference_Module_WithXxx()
        {
            var doc = new TestDocumentationProvider();
            var module = ModuleMetadata.CreateFromImage(TestResources.SymbolsTests.General.C1);
            var r = new MetadataImageReference(module, filePath: @"c:\temp", display: "hello", documentation: doc);
            Assert.Same(doc, r.DocumentationProvider);
            Assert.Same(doc, r.DocumentationProvider);
            Assert.NotNull(r.GetMetadata());
            Assert.Equal(false, r.Properties.EmbedInteropTypes);
            Assert.Equal(MetadataImageKind.Module, r.Properties.Kind);
            Assert.True(r.Properties.Aliases.IsDefault);
            Assert.Equal(@"c:\temp", r.FilePath);

            var r1 = r.WithAliases(default(ImmutableArray<string>));
            Assert.Same(r, r1);

            var r2 = r.WithEmbedInteropTypes(false);
            Assert.Same(r, r2);

            var r3 = r.WithDocumentationProvider(doc);
            Assert.Same(r, r3);
            
            Assert.Throws<ArgumentException>(() => r.WithAliases(new[] { "bar" }));
            Assert.Throws<ArgumentException>(() => r.WithEmbedInteropTypes(true));
        }
开发者ID:modulexcite,项目名称:pattern-matching-csharp,代码行数:25,代码来源:MetadataReferenceTests.cs


示例4: VersionUnification_SymbolNotUsed

        public void VersionUnification_SymbolNotUsed()
        {
            var v1 = new MetadataImageReference(TestResources.SymbolsTests.General.C1);
            var v2 = new MetadataImageReference(TestResources.SymbolsTests.General.C2);

            var refV1 = CreateCompilationWithMscorlib("public class D : C { }", new[] { v1 });
            var refV2 = CreateCompilationWithMscorlib("public class D : C { }", new[] { v2 });

            // reference asks for a lower version than available:
            var testRefV1 = CreateCompilationWithMscorlib("public class E { }", new MetadataReference[] { new CSharpCompilationReference(refV1), v2 });

            // reference asks for a higher version than available:
            var testRefV2 = CreateCompilationWithMscorlib("public class E { }", new MetadataReference[] { new CSharpCompilationReference(refV2), v1 });

            testRefV1.VerifyDiagnostics();
            testRefV2.VerifyDiagnostics();
        }
开发者ID:nagyist,项目名称:roslyn,代码行数:17,代码来源:ReferenceManagerTests.cs


示例5: VersionUnification_SymbolUsed

        public void VersionUnification_SymbolUsed()
        {
            // Identity: C, Version=1.0.0.0, Culture=neutral, PublicKeyToken=374d0c2befcd8cc9
            var v1 = new MetadataImageReference(TestResources.SymbolsTests.General.C1, display: "C, V1");

            // Identity: C, Version=2.0.0.0, Culture=neutral, PublicKeyToken=374d0c2befcd8cc9
            var v2 = new MetadataImageReference(TestResources.SymbolsTests.General.C2, display: "C, V2");

            var refV1 = CreateCompilationWithMscorlib("public class D : C { }", new[] { v1 }, assemblyName: "refV1");
            var refV2 = CreateCompilationWithMscorlib("public class D : C { }", new[] { v2 }, assemblyName: "refV2");

            // reference asks for a lower version than available:
            var testRefV1 = CreateCompilationWithMscorlib("public class E : D { }", new MetadataReference[] { new CSharpCompilationReference(refV1), v2 }, assemblyName: "testRefV1");

            // reference asks for a higher version than available:
            var testRefV2 = CreateCompilationWithMscorlib("public class E : D { }", new MetadataReference[] { new CSharpCompilationReference(refV2), v1 }, assemblyName: "testRefV2");

            // TODO (tomat): we should display paths rather than names "refV1" and "C"

            testRefV1.VerifyDiagnostics(
                // warning CS1701: 
                // Assuming assembly reference 'C, Version=1.0.0.0, Culture=neutral, PublicKeyToken=374d0c2befcd8cc9' 
                // used by 'refV1' matches identity 'C, Version=2.0.0.0, Culture=neutral, PublicKeyToken=374d0c2befcd8cc9' of 'C', you may need to supply runtime policy
                Diagnostic(ErrorCode.WRN_UnifyReferenceMajMin, "D").WithArguments(
                    "C, Version=1.0.0.0, Culture=neutral, PublicKeyToken=374d0c2befcd8cc9", 
                    "refV1",
                    "C, Version=2.0.0.0, Culture=neutral, PublicKeyToken=374d0c2befcd8cc9", 
                    "C"));

            // TODO (tomat): we should display paths rather than names "refV2" and "C"
            
            testRefV2.VerifyDiagnostics(
                // error CS1705: Assembly 'refV2' with identity 'refV2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' 
                // uses 'C, Version=2.0.0.0, Culture=neutral, PublicKeyToken=374d0c2befcd8cc9' which has a higher version than referenced assembly 
                // 'C' with identity 'C, Version=1.0.0.0, Culture=neutral, PublicKeyToken=374d0c2befcd8cc9'
                Diagnostic(ErrorCode.ERR_AssemblyMatchBadVersion, "D").WithArguments(
                    "refV2",
                    "refV2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", 
                    "C, Version=2.0.0.0, Culture=neutral, PublicKeyToken=374d0c2befcd8cc9",
                    "C",
                    "C, Version=1.0.0.0, Culture=neutral, PublicKeyToken=374d0c2befcd8cc9"));
        }
开发者ID:nagyist,项目名称:roslyn,代码行数:42,代码来源:ReferenceManagerTests.cs


示例6: ConstructedErrorTypes

        public void ConstructedErrorTypes()
        {
            var source1 =
@"public class A<T>
{
    public class B<U> { }
}";
            var compilation1 = CreateCompilationWithMscorlib(source1, assemblyName: "91AB32B7-DDDF-4E50-87EF-4E8B0A664A41");
            compilation1.VerifyDiagnostics();
            var reference1 = new MetadataImageReference(compilation1.EmitToArray(true));

            // Binding types in source, no missing types.
            var source2 =
@"class C1<T, U> : A<T>.B<U> { }
class C2<T, U> : A<T>.B<U> { }
class C3<T> : A<T>.B<object> { }
class C4<T> : A<object>.B<T> { }
class C5 : A<object>.B<int> { }
class C6 : A<string>.B<object> { }
class C7 : A<string>.B<object> { }";
            var compilation2 = CreateCompilationWithMscorlib(source2, references: new[] { reference1 }, assemblyName: "91AB32B7-DDDF-4E50-87EF-4E8B0A664A42");
            compilation2.VerifyDiagnostics();
            CompareConstructedErrorTypes(compilation2, missingTypes: false, fromSource: true);
            var reference2 = new MetadataImageReference(compilation2.EmitToArray(true));

            // Loading types from metadata, no missing types.
            var source3 =
@"";
            var compilation3 = CreateCompilationWithMscorlib(source3, references: new[] { reference1, reference2 });
            compilation3.VerifyDiagnostics();
            CompareConstructedErrorTypes(compilation3, missingTypes: false, fromSource: false);

            // Binding types in source, missing types, resulting inExtendedErrorTypeSymbols.
            var compilation4 = CreateCompilationWithMscorlib(source2);
            CompareConstructedErrorTypes(compilation4, missingTypes: true, fromSource: true);

            // Loading types from metadata, missing types, resulting in ErrorTypeSymbols.
            var source5 =
@"";
            var compilation5 = CreateCompilationWithMscorlib(source5, references: new[] { reference2 });
            CompareConstructedErrorTypes(compilation5, missingTypes: true, fromSource: false);
        }
开发者ID:modulexcite,项目名称:pattern-matching-csharp,代码行数:42,代码来源:ErrorTypeSymbolTests.cs


示例7: SameExternAliasInMultipleTreesValid

        public void SameExternAliasInMultipleTreesValid()
        {
            var comp1 = CreateCompilationWithMscorlib("public class C { }", assemblyName: "A1");
            var ref1 = new MetadataImageReference(CompileAndVerify(comp1).EmittedAssemblyData, aliases: ImmutableArray.Create("X"));

            var comp2 = CreateCompilationWithMscorlib("public class D { }", assemblyName: "A2");
            var ref2 = new MetadataImageReference(CompileAndVerify(comp2).EmittedAssemblyData, aliases: ImmutableArray.Create("X"));

            const int numFiles = 20;
            var comp3 = CreateCompilationWithMscorlib(Enumerable.Range(1, numFiles).Select(x => "extern alias X;"), new[] { ref1, ref2 }, assemblyName: "A3.dll");

            var targets = comp3.SyntaxTrees.AsParallel().Select(tree =>
            {
                var model = comp3.GetSemanticModel(tree);

                var aliasSyntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType<ExternAliasDirectiveSyntax>().Single();

                var aliasSymbol = model.GetDeclaredSymbol(aliasSyntax);
                return (NamespaceSymbol)aliasSymbol.Target;
            }).ToArray(); //force evaluation

            var firstTarget = targets.First();
            Assert.NotNull(firstTarget);
            Assert.IsType<MergedNamespaceSymbol>(firstTarget);
            firstTarget.GetMember<NamedTypeSymbol>("C");
            firstTarget.GetMember<NamedTypeSymbol>("D");

            Assert.True(targets.All(target => ReferenceEquals(firstTarget, target)));
        }
开发者ID:modulexcite,项目名称:pattern-matching-csharp,代码行数:29,代码来源:ExternAliasTests.cs


示例8: Error_ExternAliasIdentifierIsGlobalKeyword

        public void Error_ExternAliasIdentifierIsGlobalKeyword()
        {
            var src =
        @"
namespace NS
{
    public class Baz
    {
      public int M() { return 1; }
    }
}
";
            var comp = CreateCompilationWithMscorlib(src, options: TestOptions.ReleaseDll);
            var foo1Alias = new MetadataImageReference(comp.EmitToArray(), aliases: ImmutableArray.Create("global"));

            src =
            @"
extern alias global;

class Maine
{
    public static void Main()
    {
    }
}
";
            comp = CreateCompilationWithMscorlib(src);
            comp = comp.AddReferences(foo1Alias);
            comp.VerifyDiagnostics(
                // (2,14): error CS1681: You cannot redefine the global extern alias
                // extern alias global;
                Diagnostic(ErrorCode.ERR_GlobalExternAlias, "global"),
                // (2,1): info CS8020: Unused extern alias.
                // extern alias global;
                Diagnostic(ErrorCode.HDN_UnusedExternAlias, "extern alias global;"));
        }
开发者ID:modulexcite,项目名称:pattern-matching-csharp,代码行数:36,代码来源:ExternAliasTests.cs


示例9: ExternAliasDoesntFailNonSourceBinds

        public void ExternAliasDoesntFailNonSourceBinds()
        {
            // Ensure that adding an alias doesn't interfere with resolution among metadata references. The alias only affects source usage
            // of the types defined in the aliased assembly.

            var src =
        @"
namespace NS
{
    public class Baz
    {
      public int M() { return 1; }
    }
}
";
            var comp = CreateCompilationWithMscorlib(src, assemblyName: "Baz.dll", options: TestOptions.ReleaseDll);
            var outputBytes = comp.EmitToArray();
            var foo1 = new MetadataImageReference(outputBytes);
            var foo1Alias = new MetadataImageReference(outputBytes, aliases: ImmutableArray.Create("Baz"));

            src =
        @"
namespace NS
{
    public class Bar : Baz
    {
      public int M2() { return 2; }
    }
}
";
            comp = CreateCompilationWithMscorlib(src, assemblyName: "Bar.dll", options: TestOptions.ReleaseDll);
            comp = comp.AddReferences(foo1);
            var foo2 = new MetadataImageReference(comp.EmitToArray());

            src =
            @"
class Maine
{
    public static void Main()
    {
            NS.Bar d = null;
    }
}
";
            comp = CreateCompilationWithMscorlib(src);
            comp = comp.AddReferences(foo2, foo1Alias);
            comp.VerifyDiagnostics(
                // (6,20): warning CS0219: The variable 'd' is assigned but its value is never used
                //             NS.Bar d = null;
                Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "d").WithArguments("d")
            );
        }
开发者ID:modulexcite,项目名称:pattern-matching-csharp,代码行数:52,代码来源:ExternAliasTests.cs


示例10: AccessorWithImportedGenericType

        public void AccessorWithImportedGenericType()
        {
            var comp0 = CreateCompilationWithMscorlib(@"
public class MC<T> { }
public delegate void MD<T>(T t);
");

            var compref = new CSharpCompilationReference(comp0);
            var comp1 = CreateCompilationWithMscorlib(@"
using System;
public class G<T>
{
    public MC<T> Prop  {    set { }    }
    public int this[MC<T> p]  {    get { return 0;}    }
    public event MD<T> E  {     add { }  remove { }    }
}
", references: new MetadataReference[] { compref }, assemblyName: "ACCImpGen");

            var mtdata = comp1.EmitToArray(true);
            var mtref = new MetadataImageReference(mtdata);
            var comp2 = CreateCompilationWithMscorlib(@"", references: new MetadataReference[] { mtref }, assemblyName: "META");

            var tsym = comp2.GetReferencedAssemblySymbol(mtref).GlobalNamespace.GetMember<NamedTypeSymbol>("G");
            Assert.NotNull(tsym);

            var mems = tsym.GetMembers().Where(s => s.Kind == SymbolKind.Method);
            // 4 accessors + ctor
            Assert.Equal(5, mems.Count());
            foreach (MethodSymbol m in mems)
            {
                if (m.MethodKind == MethodKind.Constructor)
                    continue;

                Assert.NotNull(m.AssociatedSymbol);
                Assert.NotEqual(MethodKind.Ordinary, m.MethodKind);
            }
        }
开发者ID:riversky,项目名称:roslyn,代码行数:37,代码来源:AccessorOverriddenOrHiddenMembersTests.cs


示例11: ExternAlias

        public void ExternAlias()
        {
            var source = @"
extern alias X;

class Test
{
    static void Main()
    {
        X::C c = null;
    }
}
";
            var comp1 = CreateCompilationWithMscorlib("public class C { }");
            var ref1 = new MetadataImageReference(CompileAndVerify(comp1).EmittedAssemblyData, aliases: ImmutableArray.Create("X"));

            var comp2 = CreateCompilationWithMscorlib(source, new[] { ref1 });
            var tree = comp2.SyntaxTrees.Single();
            var model = comp2.GetSemanticModel(tree);

            var aliasSyntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType<ExternAliasDirectiveSyntax>().Single();

            // Compilation.GetExternAliasTarget defines this behavior: the target is a merged namespace
            // with the same name as the alias, contained in the global namespace of the compilation.
            var aliasSymbol = model.GetDeclaredSymbol(aliasSyntax);
            var aliasTarget = (NamespaceSymbol)aliasSymbol.Target;
            Assert.Equal(NamespaceKind.Module, aliasTarget.Extent.Kind);
            Assert.Equal("", aliasTarget.Name);
            Assert.True(aliasTarget.IsGlobalNamespace);
            Assert.Null(aliasTarget.ContainingNamespace);

            Assert.Equal(0, comp2.GlobalNamespace.GetMembers("X").Length); //Doesn't contain the alias target namespace as a child.

            var aliasQualifiedSyntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType<AliasQualifiedNameSyntax>().Single();
            Assert.Equal(aliasSymbol, model.GetAliasInfo(aliasQualifiedSyntax.Alias));

            comp2.VerifyDiagnostics(
                // (8,14): warning CS0219: The variable 'c' is assigned but its value is never used
                //         X::C c = null;
                Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "c").WithArguments("c"));
        }
开发者ID:riversky,项目名称:roslyn,代码行数:41,代码来源:SemanticModelAPITests.cs


示例12: EmitNetModuleWithReferencedNetModule

 void EmitNetModuleWithReferencedNetModule()
 {
     string source1 = @"public class A {}";
     string source2 = @"public class B: A {}";
     var comp = CreateCompilationWithMscorlib(source1, compOptions: TestOptions.NetModule);
     var metadataRef = new MetadataImageReference(ModuleMetadata.CreateFromImageStream(comp.EmitToStream()));
     CompileAndVerify(source2, additionalRefs: new[] { metadataRef }, options: TestOptions.NetModule, emitOptions: EmitOptions.RefEmitBug, verify: false);
 }
开发者ID:riversky,项目名称:roslyn,代码行数:8,代码来源:CompilationEmitTests.cs


示例13: GetIndex_IndexerWithByRefParam

        public void GetIndex_IndexerWithByRefParam()
        {
            var ilRef = new MetadataImageReference(TestResources.MetadataTests.Interop.IndexerWithByRefParam.AsImmutableOrNull());

            string source = @"
class C
{
    B b;
    dynamic d;

    object M() 
    {
        return b[d];
    }
}
";
            CompileAndVerifyIL(source, "C.M", references: new MetadataReference[] { SystemCoreRef, CSharpRef, ilRef }, expectedOptimizedIL: @"
{
  // Code size       92 (0x5c)
  .maxstack  7
  IL_0000:  ldsfld     ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, B, object, object>> C.<M>o__SiteContainer0.<>p__Site1""
  IL_0005:  brtrue.s   IL_003b
  IL_0007:  ldc.i4.0
  IL_0008:  ldtoken    ""C""
  IL_000d:  call       ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
  IL_0012:  ldc.i4.2
  IL_0013:  newarr     ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo""
  IL_0018:  dup
  IL_0019:  ldc.i4.0
  IL_001a:  ldc.i4.1
  IL_001b:  ldnull
  IL_001c:  call       ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)""
  IL_0021:  stelem.ref
  IL_0022:  dup
  IL_0023:  ldc.i4.1
  IL_0024:  ldc.i4.0
  IL_0025:  ldnull
  IL_0026:  call       ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)""
  IL_002b:  stelem.ref
  IL_002c:  call       ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.GetIndex(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)""
  IL_0031:  call       ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, B, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, B, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)""
  IL_0036:  stsfld     ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, B, object, object>> C.<M>o__SiteContainer0.<>p__Site1""
  IL_003b:  ldsfld     ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, B, object, object>> C.<M>o__SiteContainer0.<>p__Site1""
  IL_0040:  ldfld      ""System.Func<System.Runtime.CompilerServices.CallSite, B, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, B, object, object>>.Target""
  IL_0045:  ldsfld     ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, B, object, object>> C.<M>o__SiteContainer0.<>p__Site1""
  IL_004a:  ldarg.0
  IL_004b:  ldfld      ""B C.b""
  IL_0050:  ldarg.0
  IL_0051:  ldfld      ""dynamic C.d""
  IL_0056:  callvirt   ""object System.Func<System.Runtime.CompilerServices.CallSite, B, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, B, object)""
  IL_005b:  ret
}
");
        }
开发者ID:nagyist,项目名称:roslyn,代码行数:54,代码来源:CodeGenDynamicTests.cs


示例14: EmitForwarder_ModuleInReferencedAssembly

        public void EmitForwarder_ModuleInReferencedAssembly()
        {
            string moduleA = @"public class Foo{ public static string A = ""Original""; }";
            var bitsA = CreateCompilationWithMscorlib(moduleA, compOptions: TestOptions.Dll, assemblyName: "asm2").EmitToArray();
            var refA = new MetadataImageReference(bitsA);

            string moduleB = @"using System; class Program2222 { static void Main(string[] args) { Console.WriteLine(Foo.A); } }";
            var bitsB = CreateCompilationWithMscorlib(moduleB, new[] { refA }, TestOptions.Exe, assemblyName: "test").EmitToArray();

            string module0 = @"public class Foo{ public static string A = ""Substituted""; }";
            var bits0 = CreateCompilationWithMscorlib(module0, compOptions: TestOptions.NetModule, assemblyName: "asm0").EmitToArray();
            var ref0 = new MetadataImageReference(ModuleMetadata.CreateFromImage(bits0));

            string module1 = "using System;";
            var bits1 = CreateCompilationWithMscorlib(module1, new[] { ref0 }, compOptions: TestOptions.Dll, assemblyName: "asm1").EmitToArray();
            var ref1 = new MetadataImageReference(AssemblyMetadata.Create(ModuleMetadata.CreateFromImage(bits1), ModuleMetadata.CreateFromImage(bits0)));

            string module2 = @"using System; [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(Foo))]";
            var bits2 = CreateCompilationWithMscorlib(module2, new[] { ref1 }, compOptions: TestOptions.Dll, assemblyName: "asm2").EmitToArray();

            // runtime check:

            var folder = Temp.CreateDirectory();
            var folderA = folder.CreateDirectory("A");
            var folderB = folder.CreateDirectory("B");

            folderA.CreateFile("asm2.dll").WriteAllBytes(bitsA);
            var asmB = folderA.CreateFile("test.exe").WriteAllBytes(bitsB);
            var result = RunAndGetOutput(asmB.Path);
            Assert.Equal("Original", result.Trim());

            folderB.CreateFile("asm0.netmodule").WriteAllBytes(bits0);
            var asm1 = folderB.CreateFile("asm1.dll").WriteAllBytes(bits1);
            var asm2 = folderB.CreateFile("asm2.dll").WriteAllBytes(bits2);
            var asmB2 = folderB.CreateFile("test.exe").WriteAllBytes(bitsB);

            result = RunAndGetOutput(asmB2.Path);
            Assert.Equal("Substituted", result.Trim());
        }
开发者ID:EkardNT,项目名称:Roslyn,代码行数:39,代码来源:TypeForwarders.cs


示例15: Bug602893

        public void Bug602893()
        {
            var source1 =
@"namespace NA
{
    internal static class A
    {
        public static void F(this object o) { }
    }
}";
            var compilation1 = CreateCompilationWithMscorlibAndSystemCore(source1, assemblyName: "A");
            compilation1.VerifyDiagnostics();
            var compilationVerifier = CompileAndVerify(compilation1, emitOptions: EmitOptions.CCI);
            var reference1 = new MetadataImageReference(compilationVerifier.EmittedAssemblyData);
            var source2 =
@"[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""C"")]
namespace NB
{
    internal static class B
    {
        public static void F(this object o) { }
    }
}";
            var compilation2 = CreateCompilationWithMscorlibAndSystemCore(source2, assemblyName: "B");
            compilation2.VerifyDiagnostics();
            compilationVerifier = CompileAndVerify(compilation2, emitOptions: EmitOptions.CCI);
            var reference2 = new MetadataImageReference(compilationVerifier.EmittedAssemblyData);
            var source3 =
@"using NB;
namespace NA.NC
{
    class C
    {
        static void Main()
        {
            new object().F();
        }
    }
}";
            var compilation3 = CreateCompilationWithMscorlib(source3, assemblyName: "C", references: new[] { reference1, reference2 });
            compilation3.VerifyDiagnostics();
        }
开发者ID:riversky,项目名称:roslyn,代码行数:42,代码来源:ExtensionMethodTests.cs


示例16: UseTypeInNetModule

        public void UseTypeInNetModule()
        {
            var module1Ref = new MetadataImageReference(
                ModuleMetadata.CreateFromImage(TestResources.SymbolsTests.netModule.netModule1),
                display: "netModule1.netmodule");

            var text = @"class Test
{
    Class1 a = null;
}";

            var tree = SyntaxFactory.ParseSyntaxTree(text);
            var comp = CreateCompilationWithMscorlib(text, references: new[] { module1Ref });

            var globalNS = comp.SourceModule.GlobalNamespace;
            var classTest = globalNS.GetTypeMembers("Test").First();
            var varA = classTest.GetMembers("a").First() as FieldSymbol;
            Assert.Equal(SymbolKind.Field, varA.Kind);
            Assert.Equal(TypeKind.Class, varA.Type.TypeKind);
            Assert.Equal(SymbolKind.NamedType, varA.Type.Kind);
        }
开发者ID:riversky,项目名称:roslyn,代码行数:21,代码来源:TypeTests.cs


示例17: MultiDimArray

        public void MultiDimArray()
        {
            var r = new MetadataImageReference(TestResources.SymbolsTests.Methods.CSMethods.AsImmutableOrNull());
            var source = @"
class Program
{
    static void Main()
    {
        MultiDimArrays.Foo(null);
    }
}
";
            CompileAndVerify(source, new[] { r }, emitOptions: EmitOptions.RefEmitBug);
        }
开发者ID:riversky,项目名称:roslyn,代码行数:14,代码来源:TypeTests.cs


示例18: MemberSignature_LongFormType

        public void MemberSignature_LongFormType()
        {
            string source = @"
public class D
{
    public static void Main()
    {
        string s = C.RT();
        double d = C.VT();
    }
}
";
            var longFormRef = new MetadataImageReference(TestResources.MetadataTests.Invalid.LongTypeFormInSignature.AsImmutableOrNull());

            var c = CreateCompilationWithMscorlib(source, new[] { longFormRef });

            c.VerifyDiagnostics(
                // (6,20): error CS0570: 'C.RT()' is not supported by the language
                Diagnostic(ErrorCode.ERR_BindToBogus, "RT").WithArguments("C.RT()"),
                // (7,20): error CS0570: 'C.VT()' is not supported by the language
                Diagnostic(ErrorCode.ERR_BindToBogus, "VT").WithArguments("C.VT()"));
        }
开发者ID:jerriclynsjohn,项目名称:roslyn,代码行数:22,代码来源:LoadingMethods.cs


示例19: TestObsoleteAttributeInMetadata

        public void TestObsoleteAttributeInMetadata()
        {
            var peSource = @"
using System;

[Obsolete]
public class TestClass1 {}

[Obsolete(""TestClass2 is obsolete"")]
public class TestClass2 {}

[Obsolete(""Do not use TestClass3"", true)]
public class TestClass3 {}

[Obsolete(""TestClass4 is obsolete"", false)]
public class TestClass4 {}

public class TestClass
{
    [Obsolete(""Do not use TestMethod"")]
    public void TestMethod() {}

    [Obsolete(""Do not use Prop1"", false)]
    public int Prop1 { get; set; }

    [Obsolete(""Do not use field1"", true)]
    public TestClass field1;

    [Obsolete(""Do not use event"", true)]
    public Action event1;
}
";
            var peReference = new MetadataImageReference(CreateCompilationWithMscorlib(peSource).EmitToStream());

            var source = @"
public class Test
{
    public static void foo1(TestClass1 c) {}
    public static void foo2(TestClass2 c) {}
    public static void foo3(TestClass3 c) {}
    public static void foo4(TestClass4 c) {}

    public static void Main()
    {
        TestClass c = new TestClass();
        c.TestMethod();
        var i = c.Prop1;
        c = c.field1;
        c.event1();
        c.event1 += () => {};
    }
}
";
            CreateCompilationWithMscorlib(source, new[] { peReference }).VerifyDiagnostics(
                // (4,29): warning CS0612: 'TestClass1' is obsolete
                //     public static void foo1(TestClass1 c) {}
                Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "TestClass1").WithArguments("TestClass1"),
                // (5,29): warning CS0618: 'TestClass2' is obsolete: 'TestClass2 is obsolete'
                //     public static void foo2(TestClass2 c) {}
                Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "TestClass2").WithArguments("TestClass2", "TestClass2 is obsolete"),
                // (6,29): error CS0619: 'TestClass3' is obsolete: 'Do not use TestClass3'
                //     public static void foo3(TestClass3 c) {}
                Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "TestClass3").WithArguments("TestClass3", "Do not use TestClass3"),
                // (7,29): warning CS0618: 'TestClass4' is obsolete: 'TestClass4 is obsolete'
                //     public static void foo4(TestClass4 c) {}
                Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "TestClass4").WithArguments("TestClass4", "TestClass4 is obsolete"),
                // (12,9): warning CS0618: 'TestClass.TestMethod()' is obsolete: 'Do not use TestMethod'
                //         c.TestMethod();
                Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "c.TestMethod()").WithArguments("TestClass.TestMethod()", "Do not use TestMethod"),
                // (13,17): warning CS0618: 'TestClass.Prop1' is obsolete: 'Do not use Prop1'
                //         var i = c.Prop1;
                Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "c.Prop1").WithArguments("TestClass.Prop1", "Do not use Prop1"),
                // (14,13): error CS0619: 'TestClass.field1' is obsolete: 'Do not use field1'
                //         c = c.field1;
                Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "c.field1").WithArguments("TestClass.field1", "Do not use field1"),
                // (15,9): error CS0619: 'TestClass.event1' is obsolete: 'Do not use event'
                //         c.event1();
                Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "c.event1").WithArguments("TestClass.event1", "Do not use event"),
                // (16,9): error CS0619: 'TestClass.event1' is obsolete: 'Do not use event'
                //         c.event1 += () => {};
                Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "c.event1").WithArguments("TestClass.event1", "Do not use event"));
        }
开发者ID:nagyist,项目名称:roslyn,代码行数:82,代码来源:AttributeTests_WellKnownAttributes.cs


示例20: TypeForwarderInAModule

        public void TypeForwarderInAModule()
        {
            string forwardedTypes =
@"
public class CF1
{}";

            var forwardedTypesCompilation = CreateCompilationWithMscorlib(forwardedTypes, compOptions: TestOptions.Dll, assemblyName: "ForwarderTargetAssembly");

            string mod =
                @"
[assembly: System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(CF1))]
                ";

            var modCompilation = CreateCompilationWithMscorlib(mod, references: new[] { new CSharpCompilationReference(forwardedTypesCompilation) }, compOptions: TestOptions.NetModule);
            var modRef1 = modCompilation.EmitToImageReference();

            string app =
                @"
                public class Test { }
                ";

            var appCompilation = CreateCompilationWithMscorlib(app, references: new[] { modRef1, new CSharpCompilationReference(forwardedTypesCompilation) }, compOptions: TestOptions.Dll);

            var module = (PEModuleSymbol)appCompilation.Assembly.Modules[1];
            var metadata = module.Module;

            var peReader = metadata.GetMetadataReader();
            Assert.Equal(1, peReader.GetTableRowCount(TableIndex.ExportedType));
            ValidateExportedTypeRow(peReader.GetExportedTypes().First(), peReader, "CF1");

            Handle token = metadata.GetTypeRef(metadata.GetAssemblyRef("mscorlib"), "System.Runtime.CompilerServices", "AssemblyAttributesGoHereM");
            Assert.True(token.IsNil);   //could the type ref be located? If not then the attribute's not there.

            // Exported types in .Net module cause PEVerify to fail.
            CompileAndVerify(appCompilation, emitOptions: EmitOptions.RefEmitBug, verify: false,
                symbolValidator: m =>
                {
                    var peReader1 = ((PEModuleSymbol)m).Module.GetMetadataReader();
                    Assert.Equal(1, peReader1.GetTableRowCount(TableIndex.ExportedType));
                    ValidateExportedTypeRow(peReader1.GetExportedTypes().First(), peReader1, "CF1");

                    // Attributes should not actually be emitted.
                    Assert.Equal(0, m.ContainingAssembly.GetAttributes(AttributeDescription.TypeForwardedToAttribute).Count());
                }).VerifyDiagnostics();

            var ilSource = @"
.assembly extern mscorlib
{
  .publickeytoken = (B7 7A 5C 56 19 34 E0 89 )                         // .z\V.4..
  .ver 4:0:0:0
}
.assembly extern Microsoft.VisualBasic
{
  .publickeytoken = (B0 3F 5F 7F 11 D5 0A 3A )                         // .?_....:
  .ver 10:0:0:0
}
.assembly extern ForwarderTargetAssembly
{
  .ver 0:0:0:0
}
.module mod.netmodule
// MVID 

鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# MetadataObject类代码示例发布时间:2022-05-24
下一篇:
C# MetadataBuilder类代码示例发布时间:2022-05-24
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap