c# - .NETCore(Windows 8 框架)的 `GetCustomAttributes` 的等效方法是什么?

标签 c# .net windows-8 windows-runtime .net-core

我正在组装一个与 Stack API 交互的应用程序,并且一直在关注 this tutorial (虽然旧的 API 版本仍然有效)。我的问题是,在 Windows 8 商店应用程序中使用它时,我受到 .NETCore Framework 的限制,它不支持下面找到的 GetCustomAttributes 方法:

    private static IEnumerable<T> ParseJson<T>(string json) where T : class, new()
    {
        var type = typeof (T);
        var attribute = type.GetCustomAttributes(typeof (WrapperObjectAttribute), false).SingleOrDefault() as WrapperObjectAttribute;
        if (attribute == null)
        {
            throw new InvalidOperationException(
                String.Format("{0} type must be decorated with a WrapperObjectAttribute.", type.Name));
        }

        var jobject = JObject.Parse(json);
        var collection = JsonConvert.DeserializeObject<List<T>>(jobject[attribute.WrapperObject].ToString());
        return collection;
    }

我的问题有两个方面。 GetCustomAttributes 究竟做了什么?在 Windows 8 Store App 领域的约束下是否有与此方法等效的方法?

最佳答案

你需要使用type.GetTypeInfo(),它有各种GetCustomAttribute方法(通过扩展方法),或者有.CustomAttributes 它为您提供原始信息(而不是具体化的 Attribute 实例)。

例如:

var attribute = type.GetTypeInfo().GetCustomAttribute<WrapperObjectAttribute>();
if(attribute == null)
{
    ...
}
...

GetTypeInfo() 是 .NETCore 库作者的痛点;p

如果 .GetTypeInfo() 没有出现,则添加一个 using System.Reflection; 指令。

关于c# - .NETCore(Windows 8 框架)的 `GetCustomAttributes` 的等效方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12814723/

相关文章:

XAML 水平堆栈面板滚动

c# - 在没有大量新调用的情况下转换结构的 C++ 数组?

c# - .NET Core 和 Swagger API 生成

c# - 动态添加 TabItems

c# - 选择每组属性值最大的记录

windows-8 - 使 "Uninstall"命令为 Windows 8 应用程序做正确的事情

c#多维数组转换

asp.net - 无法配置IIS/Asp.NET来同时处理许多异步请求

c++ - .NET:如何以编程方式确定 .NET 应用程序是否已编译?

javascript - (Windows 8 Javascript)WinJS.xhr 不反射(reflect) api 的更改