如何从 class 获取接口?

How can I get an interface from a class?

Type objType = displayed.GetType ();
displayable = (IDisplayable)objType.GetInterface ("IDisplayable");

上面的代码给我一个错误 "Cannot cast from source to destination"。 我想得到一个 class' 接口并将其存储在一个变量中。

Type.GetInterfacereturns一个Type,不是对象。

要从对象获取接口实例,只需转换对象即可。

displayable = (IDisplayable)displayed;

如果仍然出现相同的错误,请仔细检查 displayed 的类型是否确实实现了接口 IDisplayable.