System.Type 型のユーティリティ
拡張メソッド用に TypeExtensions クラスを用意
指定した型に代入可能か判断する
Type.IsAssignableFrom メソッドがあるが、指定した型「から」なので不便
public static bool IsAssignableTo(this Type type, Type to)
{
return to?.IsAssignableFrom(type) ?? false;
}
指定したインターフェイスを実装するか判断する
public static bool HasInterface(this Type type, Type interfaceType)
{
if (type == null) throw new ArgumentNullException(nameof(type));
if (interfaceType != null)
{
foreach (var item in type.GetInterfaces())
{
if (item.Equals(interfaceType)) return true;
}
}
return false;
}
数値型か判断する
public static bool IsNumeric(this Type type) => numericTypes.Contains(type);
static Type[] numericTypes = new[] { typeof(byte), typeof(sbyte), typeof(int), typeof(uint), typeof(short), typeof(ushort), typeof(long), typeof(ulong), typeof(float), typeof(double), typeof(decimal) };
//public static bool IsNumeric(this Type type)
//{
// return type.IsPrimitive && (type != typeof(bool)) && (type != //typeof(char));
//}
Null 許容型か判断する
なぜ標準にないのか。。
public static bool IsNullable(this Type type)
{
return type.IsGenericType && (type.GetGenericTypeDefinition() == typeof(Nullable<>));
}
Null 許容型の基になる型を取得する
Null 許容型 だと Convert.ChangeType メソッドで型変換できないため、
Null 許容型の場合は基の型、それ以外はその型を使えるように。
public static Type GetUnderlyingType(this Type nullableType)
{
return nullableType.IsNullable() ? Nullable.GetUnderlyingType(nullableType) : null;
}
public static Type GetUnderlyingTypeOrSelf(this Type type)
{
return type.GetUnderlyingType() ?? type;
}
その他ユーティリティ
値が範囲内か判断
public static bool IsWithinRange<T>(this T value, T? lower, T? upper) where T : struct, IComparable<T>
{
if (lower.HasValue && (value.CompareTo(lower.Value) < 0)) return false;
if (upper.HasValue && (value.CompareTo(upper.Value) > 0)) return false;
return true;
}