将 T 转换为具有接口
本文关键字:接口 转换 | 更新日期: 2023-09-27 18:28:48
假设我有一个方法:
public void DoStuff<T>() where T : IMyInterface {
...
}
在其他地方,我想用不同的方法调用
public void OtherMethod<T>() where T : class {
...
if (typeof(T) is IMyInterface) // have ascertained that T is IMyInterface
DoStuff<T>();
}
有没有办法将 T 转换为具有我的接口?
DoStuff<(IMyInterface)T>
和其他类似的变体对我不起作用。
编辑:感谢您指出typeof(T) is IMyInterface
是检查接口的错误方法,应该在 T 的实际实例上调用。
编辑2:我发现(IMyInterface).IsAssignableFrom(typeof(T))
检查界面。
我认为最直接的方法是反思。 例如
public void OtherMethod<T>() where T : class {
if (typeof(IMyInterface).IsAssignableFrom(typeof(T))) {
MethodInfo method = this.GetType().GetMethod("DoStuff");
MethodInfo generic = method.MakeGenericMethod(typeof(T));
generic.Invoke(this, null);
}
}
您可以使用相同的语法从多个接口继承:
public void OtherMethod<T>() where T : class, IMyInterface {
...
}
这一行是错误的:
if (typeof(T) is IMyInterface) // have ascertained that T is IMyInterface
DoStuff<T>();
typeof(T)
返回一个Type
,这永远不会是一个IMyinterface
。 如果您有 T 的实例,则可以使用
if (instanceOfT is IMyInterface) // have ascertained that T is IMyInterface
DoStuff<T>();
或
if (instanceOfT is IMyInterface) // have ascertained that T is IMyInterface
DoStuff<IMyInterface>();
否则,你可以按照Tim S的建议使用反射。