我正在组装一个与 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/