2015-06-22 4 views
1

Код ниже работает без проблем в net45, но я должен использовать его в net35, что приводит к ошибке, упомянутой в заголовке, в строке 23.
Я не могу показаться найти способ исправить это в net35, который, я думаю, объясняется тем, что этот метод просто не существует в net35.System.Type не имеет определения для «GetCustomAttribute» в 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); 
     } 
    } 
} 

ответ

2

Попробуйте использовать метод расширения ниже.

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

спасибо за быстрый ответ, хорошо выглядит, но по умолчанию, наследует true или false? – LemoniscooL

+0

в порядке в соответствии с вашим изменением i полагаю, что false по умолчанию для inherit, я сделал параметр необязательным, назначив ему по умолчанию значение false. благодаря! – LemoniscooL

Смежные вопросы