Checel by som poznamenat, ze implementacia interface a dedenie z triedy je o trosku odlisne (tam si treba popytat zoznam interfacov a tie potom porovnavat ako bolo navrhovane).
using System;
using System.Windows;
namespace WpfApplication14
{
public interface IRozhranie<T> { }
public class PriamaImplementacia : IRozhranie<int> { }
public class DedenaImplementacia : PriamaImplementacia { }
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show("DedenaImplementacia -> ICloneable = " + IsDerivedFrom(new DedenaImplementacia(), typeof(ICloneable)).ToString());
MessageBox.Show("PriamaImplementacia -> IRozhranie = " + IsDerivedFrom(new PriamaImplementacia(), typeof(IRozhranie<>)).ToString());
MessageBox.Show("DedenaImplementacia -> IRozhranie = " + IsDerivedFrom(new DedenaImplementacia(), typeof(IRozhranie<>)).ToString());
MessageBox.Show("DedenaImplementacia -> PriamaImplementacia = " + IsDerivedFrom(new DedenaImplementacia(), typeof(PriamaImplementacia)).ToString());
MessageBox.Show("DedenaImplementacia -> object = " + IsDerivedFrom(new DedenaImplementacia(), typeof(object)).ToString());
MessageBox.Show("DedenaImplementacia -> string = " + IsDerivedFrom(new DedenaImplementacia(), typeof(string)).ToString());
}
public static bool IsDerivedFrom(object instance, Type checkClassType, bool inherited = true)
{
var instanceType = instance.GetType();
// GetInterfaces sa vracia mergnuty (nemusi sa ist na koren)
if (checkClassType.IsInterface)
{
foreach (var currentInterface in instanceType.GetInterfaces())
{
if (DerivedTypes(currentInterface, checkClassType))
return true;
} // foreach
return false;
} // if
// Ak sa nepytame na interface, tak pojdeme po dedenych triedach
do
{
if (DerivedTypes(instanceType, checkClassType))
return true;
if (!inherited)
return false;
instanceType = instanceType.BaseType;
} // do
while (instanceType != typeof(object));
return DerivedTypes(instanceType, checkClassType); // object
}
private static bool DerivedTypes(Type sourceType, Type checkType)
{
return (sourceType.IsGenericType ? sourceType.GetGenericTypeDefinition() : sourceType) == checkType;
}
}
}