gpt4 book ai didi

c# - 有人可以解释这段 MVVM 代码吗

转载 作者:太空宇宙 更新时间:2023-11-03 22:30:14 25 4
gpt4 key购买 nike

我正在尝试这个 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;
}
}

任何人都可以给我逐行描述这段代码吗?发生了很多事情,我无法完全处理。

最佳答案

大多数这些概念在 the official documentation 中都有很好的解释。 .

有了这个,我将尝试解释下面的每一行:

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

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

protected T This;

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

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

添加一个 implicit conversion来自 NotificationBase<T>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;
}

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

关于c# - 有人可以解释这段 MVVM 代码吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58264029/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com