获取模型的所有非数字属性
Get all properties of a model that are not a number
假设我有这样的模型(我把它缩短了一点):
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 等进行比较?
没有等同于 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);
}
}
假设我有这样的模型(我把它缩短了一点):
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 等进行比较?
没有等同于 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);
}
}