2015-06-25 2 views
0

Предполагая, что у меня есть модель, как это (я укоротить его немного):Получить все свойства модели, которые не число

class NewsletterDatum 
{ 
    public string FullName{ get; set; } 
    public string Email { get; set; } 
    public string OptOutLink { get; set; } 
    public long ConciergeId { get; set; } 
    public long AwardCount { get; set; } 
    public int YearsMember {get; set; } 
    public string CardNumber { get; set; } 
    public string MemberName { get; set; } 
    public string PointBalance { get; set; } 
    public List<string> StoredKeyWords { get; set; } 
    public List<string> FriendIds { get; set; } 
} 

Я хочу, чтобы получить список свойств этой модели, которые не являются численный, есть ли способ сделать это, не сравнивая типы с int, long, decimal и т. д.?

+0

Вы хотите получить тип данных свойств без сравнения с существующими типами данных? Я не вижу, как это должно работать. – HimBromBeere

+0

Связанный вопрос: http://stackoverflow.com/questions/124411/using-net-how-can-i-determine-if-a-type-is-a-numeric-valuetype – RQDQ

+0

Также связано: http: // stackoverflow .com/questions/1749966/c-sharp-how-to-define-a-type-is-a-number – HimBromBeere

ответ

3

Нет эквивалента Type.IsNumeric().

Я создал метод расширения для этого. Он реализован в VB, но может быть выполнен на C#.

public static class TypeExtensions { 
    private static HashSet<Type> NumericTypes = new HashSet<Type> { 
     typeof(byte), 
     typeof(sbyte), 
     typeof(short), 
     typeof(ushort), 
     typeof(int), 
     typeof(uint), 
     typeof(long), 
     typeof(ulong), 
     typeof(float), 
     typeof(double), 
     typeof(decimal), 
     typeof(IntPtr), 
     typeof(UIntPtr), 
    }; 

    private static HashSet<Type> NullableNumericTypes = new HashSet<Type>(
     from type in NumericTypes 
     select typeof(Nullable<>).MakeGenericType(type) 
    ); 

    public static bool IsNumeric(this Type @this, bool allowNullable = false) { 
     return NumericTypes.Contains(@this) 
      || allowNullable && NullableNumericTypes.Contains(@this); 
    } 
} 
+0

Я получаю идею, метод расширения, спасибо! –

+2

@YuvalItzchakov: Я его преобразовал. – recursive

+0

Спасибо .NET virtuoso. –

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