在C#
中,反射是否提供了一种确定某个给定的System.Type
类型是否模拟某个接口的方法?
public interface IMyInterface {}
public class MyType : IMyInterface {}
// should yield 'true'
typeof(MyType)./* ????? */MODELS_INTERFACE(IMyInterface);
在C#
中,反射是否提供了一种确定某个给定的System.Type
类型是否模拟某个接口的方法?
public interface IMyInterface {}
public class MyType : IMyInterface {}
// should yield 'true'
typeof(MyType)./* ????? */MODELS_INTERFACE(IMyInterface);
如果有人在寻找此内容,可能会发现以下扩展方法很有用:
public static class TypeExtensions
{
public static bool ImplementsInterface(this Type type, Type @interface)
{
if (type == null)
{
throw new ArgumentNullException(nameof(type));
}
if (@interface == null)
{
throw new ArgumentNullException(nameof(@interface));
}
var interfaces = type.GetInterfaces();
if (@interface.IsGenericTypeDefinition)
{
foreach (var item in interfaces)
{
if (item.IsConstructedGenericType && item.GetGenericTypeDefinition() == @interface)
{
return true;
}
}
}
else
{
foreach (var item in interfaces)
{
if (item == @interface)
{
return true;
}
}
}
return false;
}
}
xunit测试:
public class TypeExtensionTests
{
[Theory]
[InlineData(typeof(string), typeof(IList<int>), false)]
[InlineData(typeof(List<>), typeof(IList<int>), false)]
[InlineData(typeof(List<>), typeof(IList<>), true)]
[InlineData(typeof(List<int>), typeof(IList<>), true)]
[InlineData(typeof(List<int>), typeof(IList<int>), true)]
[InlineData(typeof(List<int>), typeof(IList<string>), false)]
public void ValidateTypeImplementsInterface(Type type, Type @interface, bool expect)
{
var output = type.ImplementsInterface(@interface);
Assert.Equal(expect, output);
}
}
IsAssignableFrom
现在已经移动到TypeInfo
中:
typeof(ISMSRequest).GetTypeInfo().IsAssignableFrom(typeof(T).GetTypeInfo());
typeof(MyType).GetInterface(nameof(IMyInterface)) != null;
typeof(MyType).IsAssignableFrom(typeof(IMyInterface));
static void TestIConvertible()
{
string test = "test";
Type stringType = typeof(string); // or test.GetType();
bool isConvertibleDirect = test is IConvertible;
bool isConvertibleTypeAssignable = stringType.IsAssignableFrom(typeof(IConvertible));
bool isConvertibleHasInterface = stringType.GetInterface(nameof(IConvertible)) != null;
Console.WriteLine($"isConvertibleDirect: {isConvertibleDirect}");
Console.WriteLine($"isConvertibleTypeAssignable: {isConvertibleTypeAssignable}");
Console.WriteLine($"isConvertibleHasInterface: {isConvertibleHasInterface}");
}
isConvertibleDirect: True
isConvertibleTypeAssignable: False
isConvertibleHasInterface: True
怎么样?
if(MyType as IMyInterface != null)
?
关于什么?
typeof(IWhatever).GetTypeInfo().IsInterface
if(myObject is IMyInterface )
{
// it's implementing IMyInterface
}
IsAssignableFrom
时交换了类型。就像Benjamin和Ehouarn警告的那样。 - VV5198722