c# - 如何在 WP8.1 应用程序中使用反射获取命名空间中的所有类?

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

稍后我想使用像这样的方法使用反射创建我的每个实体:

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

我为什么要尝试这样做?因为这不是我第一次使用 SQLite,所以我想创建一个标准方法来简化我的工作。感谢您提供有值(value)的知识。

最佳答案

GetExecutingAssembly 在 WinRT 中不可用,但您可以改用 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));

关于c# - 如何在 WP8.1 应用程序中使用反射获取命名空间中的所有类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28376875/

相关文章:

xaml - 滚动到 ScrollViewer 结尾的最佳方式

c# - 在 Windows 8 文本框中突出显示文本

c# - 服务器无法运行

c# - 如何使用反射获取调用方法名称和类型?

c# - 没有给出与 'firstName' 所需的形参 'Person.Person(string, string)' 相对应的参数

java - 在 Android 中使用反射是一个糟糕的设计吗?

c# - 从类创建数据表(不是实例列表)

c# - WinRT 在哪里存储 RSA 私钥

C# 子查询不工作

c# - CompositeControls 上的数据绑定(bind)