简体   繁体   中英

In NetStandard 1.3: How I get all classes that implement an interface to avoid the Error CS0117 'Assembly' does not contain a definition

I tried to use this code in a NetStandard 1.3 class library:

    foreach (Type mytype in System.Reflection.Assembly.GetExecutingAssembly().GetTypes()
    .Where(mytype => mytype .GetInterfaces().Contains(typeof(myInterface)))) {
        //do stuff
     }

but a compilation error is raised:

    Error   CS0117  'Assembly' does not contain a definition for 'GetExecutingAssembly'

I reached What is the equivalent of Assembly.GetEntryAssembly() in .NET Core? , but it can't help.

I know that this service may be available in NetStandard 2, but until it's released(it's now in preview):

What is the modification to be done to the above code to support NetStandard 1.3

Update:

The question isn't a duplicate, i mentioned this link in my question and said it doesn't help.

Based on the comment of @ mjwills, it's probably worth adding that it's best to avoid using netstandard 1.5 or 1.6, as they won't be compatible with netstandard 2.0 https://blogs.msdn.microsoft.com/dotnet/2016/09/26/introducing-net-standard/#div-comment-136675

C# library for .NET Core and .NET Framework

I ask for an equivalent code (not necessary using GetExecutingAssembly):

How I get all classes that implement an interface in NetStandard 1.1 up to 1.4 ?

The following code is running in NetStandard1.3 and get all classes that implement interface without compilation error:

            Assembly asm = typeof(ICustomeAttribute).GetTypeInfo().Assembly; //thanks to @mjwills  for his helpfull comment

            var types = asm.DefinedTypes.Where(x=>x.ImplementedInterfaces.Contains(typeof(ICustomeAttribute)));
            foreach (var type in types)
            {
                //do stuff
                Console.WriteLine("class name: {0} - {1}",type.Name,type.FullName);
            }

Remarks

Excerpt from: Assembly.DefinedTypes Property

The DefinedTypes property is comparable to the Assembly.GetTypes method, except that the DefinedTypes property returns a collection of TypeInfo objects, and the Assembly.GetTypes method returns an array of Type objects.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM