什么是.NETCore(Windows 8 Framework)的GetCustomAttributes的等效方法?

问题描述:

我正在将一个应用程序与Stack API进行接口,并且已经遵循this tutorial(尽管旧API版本仍然有效)。我的问题是,在Windows 8 Store应用中使用这个时候我被.NETCore框架,它不支持GetCustomAttributes方法如下发现contrained:什么是.NETCore(Windows 8 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;指令。

+1

我花了大约两个小时试图找到这个。应该早点问:P – KronoS

+1

@KronoS heh;我很高兴能够转换现有的反映广泛使用的库......我和.NETCore现在都非常了解对方,而且不是很好。这只是冰山一角,如果你做了大量的反思; p –

+2

有一点要添加.NetCore(与xproj),TypeInfo扩展名在“System.Reflection.Extensions”包:“dotnet5.4”:{ “dependencies”:{“System.Reflection.Extensions”:“4.0.1-beta-23516” } } – Spi

System.Reflection.TypeExtensions块金包添加到您的项目;它具有GetCustomAttributes扩展。

(对于VS 2017)就像这样。

<ItemGroup Condition="'$(TargetFramework)' == 'netstandard1.6'"> 
    <PackageReference Include="System.Reflection.TypeExtensions"> 
     <Version>4.3.0</Version> 
    </PackageReference> 
</ItemGroup>