c# - 如何链接不同班级的两个代表?
问题描述
我有两个不同的课程,比如说Outer
和Inner
。的一个实例Inner
是Outer
. 我的目标是链接ActionInner
and ActionOuter
; 换句话说,当我为 添加一个动作时ActionOuter
,我希望它被添加到ActionInner
. 我该怎么做?
这是我的尝试不起作用,因为这两个动作都是空值:
class Program
{
static void Main()
{
Outer outer = new Outer();
void writeToConsole(double foo)
{
Console.WriteLine(foo);
}
// Here I expect to link the 'writeToConsole' action to 'inner' 'ActionInner'
outer.ActionOuter += writeToConsole;
// Here I expect an instance of 'inner' to output '12.34' in console
outer.StartAction();
Console.ReadKey();
}
}
class Inner
{
public Action<double> ActionInner;
public void DoSomeStuff(double foo)
{
ActionInner?.Invoke(foo);
}
}
class Outer
{
readonly Inner inner;
public Action<double> ActionOuter;
public void StartAction()
{
inner.DoSomeStuff(12.34);
}
public Outer()
{
inner = new Inner();
// Here I want to somehow make a link between two actions
inner.ActionInner += ActionOuter;
}
}
解决方案
ActionOuter
将字段更改为属性。设置并获得如下所示;
public Action<double> ActionOuter
{
set => inner.ActionInner = value;
get => inner.ActionInner;
}
推荐阅读
- c# - C# 使用 SimpleJSON 写入 json 文件
- python - ElasticSearch Scroll api 问题
- c# - 如何获取每个文件夹的文件数
- c# - 如何改变每次碰撞时的音高?
- python - 在openpyxl中读取单元格编号格式
- ios - 为什么我的 SKSpriteNode 没有按照代码的意图直线移动?
- php - 正则表达式匹配字幕中的 SRT 和 VTT 语法
- ruby - 有没有办法在我的 sinatra 应用程序中使用不同的 mime 类型
- json - DjangoRestFramework:在 JsonField 中搜索和排序元素
- node.js - 调用链码时出错,节点 SDK,方法:channel.sendTransactionProposal()