gpt4 book ai didi

c# - object - 最顶层的基类如何获得方法。 [扩展方法]

转载 作者:行者123 更新时间:2023-11-30 20:11:01 25 4
gpt4 key购买 nike

昨天我经历了一些article关于EventAggregator,有一些这样写的代码,

(Message.Text as object).PublishEvent(PublishEventNames.MessageTextChanged);

public static class ExtensionServices
{
//Supplying event broking mechanizm to each object in the application.
public static void PublishEvent<TEventsubject>(this TEventsubject eventArgs, string eventTopic)
{
ServicesFactory.EventService.GetEvent<GenericEvent<TEventsubject>>()
.Publish(new EventParameters<TEventsubject> { Topic = eventTopic, Value = eventArgs });
}
}

我的问题是,对象如何获得方法“PublishEvent”。我对 OOP 的理解有误吗?

最佳答案

它被实现为 Extension Methodobject 类上。

例如,这个扩展方法(来自链接文章):

public static class MyExtensions
{
public static int WordCount(this String str)
{
return str.Split(new char[] { ' ', '.', '?' },
StringSplitOptions.RemoveEmptyEntries).Length;
}
}

String 类上定义(通过使用 this String 语法和静态类上的静态方法)。

String 中定义的项目现在有一个 WordCount 方法(只要它也在正确的命名空间中)。

关于c# - object - 最顶层的基类如何获得方法。 [扩展方法],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4338333/

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