System.Type 在 net35 中没有“GetCustomAttribute”的定义

Lem*_*ooL 2 c#

下面的代码在net45中工作没有问题,但我必须在net35中使用它,这会导致标题中提到的错误,第23行。
我似乎找不到在net35中修复它的方法,我认为这是因为net35 中根本不存在该方法。

对于扩展方法或如何修复它有什么想法吗?

using System;
using System.Collections.Generic;
using System.Reflection;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using TwitchCSharp.Models;

namespace TwitchCSharp.Helpers
{
    // @author gibletto
    class TwitchListConverter : JsonConverter
    {

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            throw new NotImplementedException();
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            var value = Activator.CreateInstance(objectType) as TwitchResponse;
            var genericArg = objectType.GetGenericArguments()[0];
            var key = genericArg.GetCustomAttribute<JsonObjectAttribute>();
            if (value == null || key == null)
                return null;
            var jsonObject = JObject.Load(reader);
            value.Total = SetValue<long>(jsonObject["_total"]);
            value.Error = SetValue<string>(jsonObject["error"]);
            value.Message = SetValue<string>(jsonObject["message"]);
            var list = jsonObject[key.Id];
            var prop = value.GetType().GetProperty("List");
            if (prop != null && list != null)
            {
                prop.SetValue(value, list.ToObject(prop.PropertyType, serializer), null);
            }
            return value;
        }


        public override bool CanConvert(Type objectType)
        {
            return objectType.IsGenericType && typeof(TwitchList<>) == objectType.GetGenericTypeDefinition();
        }

        private T SetValue<T>(JToken token)
        {
            if (token != null)
            {
                return (T)token.ToObject(typeof(T));
            }
            return default(T);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Sar*_*thy 5

尝试下面的扩展方法。

public static T GetCustomAttribute<T>(this Type type, bool inherit) where T : Attribute
{
    object[] attributes = type.GetCustomAttributes(inherit);
    return attributes.OfType<T>().FirstOrDefault();
}
Run Code Online (Sandbox Code Playgroud)

编辑:没有任何参数。

public static T GetCustomAttribute<T>(this Type type) where T : Attribute
{
    // Send inherit as false if you want the attribute to be searched only on the type. If you want to search the complete inheritance hierarchy, set the parameter to true.
    object[] attributes = type.GetCustomAttributes(false);
    return attributes.OfType<T>().FirstOrDefault();
}
Run Code Online (Sandbox Code Playgroud)