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

本文关键字:定义 GetCustomAttribute Type net35 System | 更新日期: 2023-09-27 17:57:23

下面的代码在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);
        }
    }
}

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

尝试以下扩展方法。

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

编辑:没有任何参数。

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();
}