Вы не можете сравнить два double
с фиксированным EPSILON
. В зависимости от значения double
изменяется EPSILON
.
Лучшее двойное сравнение было бы:
bool same(double a, double b)
{
return std::nextafter(a, std::numeric_limits<double>::lowest()) <= b
&& std::nextafter(a, std::numeric_limits<double>::max()) >= b;
}
Используя ответ от TcK, это также можно сделать со следующим запросом LINQ:
bool isBar = foo.GetType().GetInterfaces().Any(x =>
x.IsGenericType &&
x.GetGenericTypeDefinition() == typeof(IBar<>));
Вы должны проверить на построенный тип общего интерфейса.
Вам нужно будет сделать что-то вроде этого:
foo is IBar<String>
, потому что IBar<String>
представляет построенный тип , Причина, по которой вы должны это сделать, состоит в том, что если T
не определено в вашей проверке, компилятор не знает, имеете ли вы IBar<Int32>
или IBar<SomethingElse>
.
Я использую немного более простую версию метода расширения @GenericProgrammers:
public static bool Implements<TInterface>(this Type type) where TInterface : class {
var interfaceType = typeof(TInterface);
if (!interfaceType.IsInterface)
throw new InvalidOperationException("Only interfaces can be implemented.");
return (interfaceType.IsAssignableFrom(type));
}
Использование:
if (!featureType.Implements<IFeature>())
throw new InvalidCastException();
Вам нужно пройти через дерево наследования и найти все интерфейсы для каждого класса в дереве и сравнить typeof(IBar<>)
с результатом вызова Type.GetGenericTypeDefinition
, если интерфейс является общим. Конечно, это немного больно.
Для получения дополнительной информации и кода см. этот ответ и для этих .
Способ проверки того, наследует ли тип или реализует общий тип:
public static bool IsTheGenericType(this Type candidateType, Type genericType)
{
return
candidateType != null && genericType != null &&
(candidateType.IsGenericType && candidateType.GetGenericTypeDefinition() == genericType ||
candidateType.GetInterfaces().Any(i => i.IsGenericType && i.GetGenericTypeDefinition() == genericType) ||
candidateType.BaseType != null && candidateType.BaseType.IsTheGenericType(genericType));
}
Прежде всего public class Foo : IFoo<T> {}
не компилируется, потому что вам нужно указать класс вместо T, но если вы сделаете что-то вроде public class Foo : IFoo<SomeClass> {}
, то если вы
Foo f = new Foo();
IBar<SomeClass> b = f as IBar<SomeClass>;
if(b != null) //derives from IBar<>
Blabla();
Не должно быть ничего плохого:
bool implementsGeneric = (anObject.Implements("IBar`1") != null);
Для дополнительного кредита вы можете поймать AmbiguousMatchException, если вы хотите указать конкретный общий тип-параметр с запросом IBar.
bool implementsGeneric = (anObject.Implements(typeof(IBar<>).Name) != null);
– Maxime Gélinas
17 June 2017 в 02:39
Если вам нужен метод расширения, который будет поддерживать общие базовые типы, а также интерфейсы, я расширил ответ sduplooy:
public static bool InheritsFrom(this Type t1, Type t2)
{
if (null == t1 || null == t2)
return false;
if (null != t1.BaseType &&
t1.BaseType.IsGenericType &&
t1.BaseType.GetGenericTypeDefinition() == t2)
{
return true;
}
if (InheritsFrom(t1.BaseType, t2))
return true;
return
(t2.IsAssignableFrom(t1) && t1 != t2)
||
t1.GetInterfaces().Any(x =>
x.IsGenericType &&
x.GetGenericTypeDefinition() == t2);
}
Чтобы полностью решить систему типов, я думаю, вам нужно обрабатывать рекурсию, например. IList<T>
: ICollection<T>
: IEnumerable<T>
, без которого вы не знали бы, что IList<int>
в конечном итоге реализует IEnumerable<>
.
/// <summary>Determines whether a type, like IList<int>, implements an open generic interface, like
/// IEnumerable<>. Note that this only checks against *interfaces*.</summary>
/// <param name="candidateType">The type to check.</param>
/// <param name="openGenericInterfaceType">The open generic type which it may impelement</param>
/// <returns>Whether the candidate type implements the open interface.</returns>
public static bool ImplementsOpenGenericInterface(this Type candidateType, Type openGenericInterfaceType)
{
Contract.Requires(candidateType != null);
Contract.Requires(openGenericInterfaceType != null);
return
candidateType.Equals(openGenericInterfaceType) ||
(candidateType.IsGenericType && candidateType.GetGenericTypeDefinition().Equals(openGenericInterfaceType)) ||
candidateType.GetInterfaces().Any(i => i.IsGenericType && i.ImplementsOpenGenericInterface(openGenericInterfaceType));
}
public interface IFoo<T> : IBar<T> {}
public class Foo : IFoo<Foo> {}
var implementedInterfaces = typeof( Foo ).GetInterfaces();
foreach( var interfaceType in implementedInterfaces ) {
if ( false == interfaceType.IsGeneric ) { continue; }
var genericType = interfaceType.GetGenericTypeDefinition();
if ( genericType == typeof( IFoo<> ) ) {
// do something !
break;
}
}