System.Type has no definition for "GetCustomAttribute" in net35

The code below works without problems in net45, but I have to use it in net35, which leads to the error mentioned in the header on line 23.
I cannot find a way to fix this in net35, which I think is explained by the fact that this method just does not exist in net35.

Any idea for an extension method or how to fix it otherwise?

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);
        }
    }
}
+1
source share
1 answer

Try using the following extension method.

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

Edit: Without any options.

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

Source: https://habr.com/ru/post/1606075/


All Articles