【问题标题】:What is an equivalent method to `GetCustomAttributes` for .NETCore (Windows 8 Framework)?.NETCore(Windows 8 Framework)的“GetCustomAttributes”的等效方法是什么?
【发布时间】:2012-09-30 15:38:15
【问题描述】:

我正在制作一个与 Stack API 交互的应用程序,并且一直在关注 this tutorial(尽管旧的 API 版本仍然有效)。我的问题是,在 Windows 8 Store App 中使用它时,我受到 .NETCore 框架的限制,它不支持下面的 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 应用商店应用领域的限制内是否有与此方法等效的方法?

【问题讨论】:

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


    【解决方案1】:

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

    例如:

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

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

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

    【讨论】:

    • 我花了大约两个小时试图找到这个。应该早点问:P
    • @KronoS 嘿;我有幸转换了一个广泛使用反射的现有库......我和 .NETCore 现在彼此非常了解,而且不是很好。如果您进行大量反思,这只是冰山一角;p
    • 在 .NetCore(使用 xproj)上添加一件事,TypeInfo 扩展位于“System.Reflection.Extensions”包中:“dotnet5.4”:{“dependencies”:{“System.Reflection .Extensions": "4.0.1-beta-23516" } }
    【解决方案2】:

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

    (对于 VS 2017)类似这样的东西。

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

    【讨论】:

      猜你喜欢
      • 2011-05-18
      • 1970-01-01
      • 1970-01-01
      • 2012-04-18
      • 2011-01-21
      • 2012-12-27
      • 1970-01-01
      • 2012-07-05
      相关资源
      最近更新 更多