通过操作/委托对泛型对象进行C#方法调用(kotlin示例)



我想调用C#中泛型对象的方法调用。我似乎不知道该怎么做。我将发布一个kotlin的例子,我是如何在我们的android应用程序中为MVP模式做到这一点的。

基本演示器通用实现:

interface IBasePresenter<in T> {
fun takeView(view: T)
fun dropView()
}
class BasePresenter<T> : IBasePresenter<T> {
private var view: T? = null
final override fun takeView(view: T) {
this.view = view
}
final override fun dropView() {
view = null
}
fun onView(action: T.() -> Unit) {
if (view != null) {
action.invoke(view!!) // Magic :-)
}
}
}

MVP实施的简单合同:

interface IMyView {
fun doSomeRendering(int width, int height)
}
interface IMyPresenter : IBasePresenter<IMyView> {
fun onButtonClicked()
}

视图和演示器的实现:

class MyView : Fragment(), IMyView {
....
override fun doSomeRendering(int width, int height) {
// Do some rendering with width and height...
}
....
}
class MyPresenter : BasePresenter<IMyView> {
override fun onButtonClicked() {
// onView action block is context aware of IMyView functions...
onView { doSomeRendering(800, 400) } // Magic :-)
}
}

除了以下内容之外,我在C#中设置了所有内容:

fun onView(action: T.() -> Unit) {
if (view != null) {
action.invoke(view!!)
}
}

这可以像在kotlin中一样在C#中完成吗?我所需要的只是能够在具体的演示器实现中执行以下调用

onView { doSomeRendering(800, 400) }

这样,我就可以在BasePresenter中保持我的视图私有,而不将其公开给具体的实现。

所以我想出了如何做到这一点。以下代码适用于C#:

基础演示器实现:

void OnView(Action<TView> action) => action(_view)

来自具体演示者实现的调用:

OnView(view => view.DoSomeRendering(800, 400))

因此,视图不再需要在基本呈现程序中受到保护,可以是私有的。

最新更新