如何使用WP8.1 App中的Reflection获取命名空间中的所有类?

时间:2015-02-07 00:04:46

标签: c# reflection windows-runtime windows-phone-8.1 win-universal-app

我已经阅读了几篇关于如何使用反射获取类的帖子,即使在StackOverflow中有不同的例子,但它们都没有与此版本的WP或Windows相关,如果你尝试这些代码,它们的工作原理都没有。这是我尝试的最后一个:

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()));

我希望有人可以给我任何想法,因为当我尝试类似的东西时,VS总是告诉我:'System.Reflection.Assembly'不包含'GetExecutingAssembly'的定义。

我正在尝试使用此功能,但我不确定如何更改它。 Reflection WinRT

这是我的班级:

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; }
    }
}

后来我想用一个像这样的方法使用Reflection创建我的每个实体:

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

为什么我要这样做?因为这不是我第一次使用SQLite而且我想创建一个标准方法来使我的工作更轻松。感谢您的宝贵知识。

1 个答案:

答案 0 :(得分:3)

WinRT中不提供

GetExecutingAssembly,但您可以使用typeof(AClassInYourAssembly).GetTypeInfo().Assembly代替。

    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));