简体   繁体   中英

How to get all classes in a Namespace using Reflection in a WP8.1 App?

I have read several posts about how to get Classes using reflection even there are different examples in StackOverflow but none of them is related to this Version of WP or Windows and if you try those codes no of them works. This is the last one that I tried:

string @namespace = "Supernova.Entities";

var types = Assembly.GetExecutingAssembly().GetTypes()
    .Where(t => t.IsClass && t.Namespace == @namespace)
    .ToList();

types.ForEach(t => Console.WriteLine(t.Name.GetType()));

I hope someone could give me an idea because when I tried something like that VS always told me: 'System.Reflection.Assembly' does not contain a definition for 'GetExecutingAssembly'.

I'm trying to use this but I'm not sure how to change it. Reflection WinRT

This is my class:

namespace Supernova.Entities
{
    public class profile
    {
        [PrimaryKey]
        public string email { get; set; }
        public string firstName { get; set; }
        public string lastName { get; set; }
    }

    public class bloodResults
    {
        [PrimaryKey, AutoIncrement]
        public int idbloodresult { get; set; }
        public double result { get; set; }
    }
}

Later I want to create each of my entities using Reflection with a method like this one:

public static async void CreateDatabase()
{
   var profile = await ConnectionDb().CreateTableAsync<profile>();
   var bloodresults = await ConnectionDb().CreateTableAsync<bloodResults>();
}

Why am I trying to do this? Because this is not my first time using SQLite and I'd like to create a standard method to make my work easier. Thanks for your worthy knowledge.

GetExecutingAssembly is not available in WinRT, but you can use typeof(AClassInYourAssembly).GetTypeInfo().Assembly instead.

    string @namespace = "Supernova.Entities";
    var assembly = typeof(YourClass).GetTypeInfo().Assembly;
    var types = assembly.GetTypes()
        .Where(t => t.GetTypeInfo().IsClass && t.Namespace == @namespace)
        .ToList();

    types.ForEach(t => Console.WriteLine(t.Name));

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