【问题标题】:Can someone explain this bit of MVVM code有人可以解释这段 MVVM 代码吗
【发布时间】:2020-02-04 10:09:16
【问题描述】:

我正在尝试这个 MVVM 的东西,并且正在关闭 John Shews (A Minimal MVVM UWP App) 的博客文章。我想我了解大部分情况,除了NotificationBase 文件中的一小部分。

这是我无法理解的部分。

public class NotificationBase<T> : NotificationBase where T : class, new()
{
    protected T This;

    public static implicit operator T(NotificationBase<T> thing) { return thing.This; }

    public NotificationBase(T thing = null)
    {
        This = (thing == null) ? new T() : thing;
    }
}

谁能给我这段代码的逐行描述?发生了一堆我无法处理的事情。

【问题讨论】:

标签: c# mvvm uwp


【解决方案1】:

大部分这些概念在the official documentation 中都有很好的解释。

除此之外,我将尝试在下面解释每一行:

public class NotificationBase<T> : NotificationBase where T : class, new()

声明一个名为 NotificationBase&lt;T&gt; 的新类,它有一个泛型类型参数 (T)。它派生自类NotificationBase(非通用版本)。它对类型参数有两个约束;它必须是class(即引用类型,而不是枚举或其他整数类型),并且必须有一个可见的空构造函数(由new() 约束决定)。

protected T This;

声明一个名为Thisprotected 字段。您可以在此类的实例和派生对象中使用该字段。

public static implicit operator T(NotificationBase<T> thing) { return thing.This; }

implicit conversionNotificationBase&lt;T&gt; 添加到T,以便您可以执行以下操作(示例):

NotificationBase<string> myWrappedString = new NotificationBase<string>("Heya");
string myString = myWrappedString;
// implicit conversion is supported due to the implicit operator declared above.
public NotificationBase(T thing = null)
{
    This = (thing == null) ? new T() : thing;
}

声明一个公共构造函数,以便您可以创建NotificationBase&lt;T&gt; 的实例。如果输入是null,构造函数将只是new 增加一个T 类型的东西(不管它是什么,只要它有一个空的构造函数)。 ternary operator (predicate ? then : else) 用于在分配给This 字段时使代码紧凑且可读。

【讨论】:

  • 可能他不了解 MVVM 上下文,但非常了解泛型等单一语言元素。
  • @UweKeim 该人说:“谁能给我逐行描述这段代码?有很多东西我无法理解处理。”。我只是假设这是他们想要的:-)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-09-14
  • 1970-01-01
  • 2011-08-20
  • 1970-01-01
  • 1970-01-01
  • 2017-05-09
相关资源
最近更新 更多